PHP 简易聊天室实例

http://tech.ddvip.com   2007年01月18日    社区交流

本文详细介绍PHP 简易聊天室实例

<html>
<head>
<title>简易聊天室(作者:东方一蛇(http://phpinto.126.com))</title>
</head>
<body bgcolor="#cccccc" topalign=0>
<?
#说明:为了避免重复,再加上我本人比较懒,以下所有注释我没有在该文件中说明,您可以在本人的网站上看(http://phpinto.126.com)
                       
# 注释1
$name = str_replace ( "<", "<", $name);
$name = str_replace ( ">", ">", $name);
$name = stripslashes (trim($name));
?>
<table border=0>
<form action="input.php" method="post">
<tr>
 <td>
房间:<font color=blue><? echo $room; ?></font>
<input type="hidden" name="room" value="<? echo $room; ?>">
大名: <font color=blue><? echo $name; ?></font><font style="font-size:9pt;color=color:#cccccc">      有任何问题或建议请去<a href="http://phpinto.126.com" target=home>主页</a>联系<a href="mailto:greenchn@163.net">东方一蛇</a></font><br>
</td>
</tr>
<tr>
<td>
<input type="hidden" name="name" value="<? echo $name; ?>">
内容: <input type="text" name="message" size=75>
<input type="submit" value="确定">
</form>
</td>
</tr>
<?
$t = date(d日H时i分);            # 注释2
$talk = 100;                 # 注释3
$r = 25;                   # 注释4
switch ($room) {
 
case '大厅':
    
$write_file="1.txt";
    
break;
 
case '客房':
    
$write_file="2.txt";
    
break;
 
case '后院':
    
$write_file="3.txt";
    
break;
 
default:
    
$write_file="0.txt";
    
break;
}
$max_file_size = $r * ($talk+15);       # 注释5
$file_size= filesize($chat_file);
     
if ($file_size > $max_file_size) {
 
$lines = file($write_file);
 
$tmp= count($lines);
 
$u = $tmp - $r;
 
for($i = $tmp; $i >= $u ;$i--)
     
{
      
$msg_old = $lines[$i] . $msg_old;
     
}
 
$deleted = unlink($write_file);    # 注释6
 
$fp = fopen($write_file, "a+");   # 注释7
 
$fw = fwrite($fp, $msg_old);
 
fclose($fp);
}
$msg = str_replace ( "
", " ", $message);
$msg = str_replace ( "<", "<",$msg);
$msg = str_replace ( ">", ">",$msg);
$msg = stripslashes ($msg);    
if ($msg != ""){
 
$fp = fopen($write_file, "a+");
 
$fw = fwrite($fp, "
<b>[$t]$name :</b> $msg");   # 注释8
 
fclose($fp);
}
?>
</body>
</html>

  注释说明

  注释1:这里处理“<”和“>”符号,上面的显示可能有问题,您应该将第二个“<”(或“>”)变成“&”加上“lt”(或“gt”)

  注释2:函数date的用法请大家参考有关文档

  注释3:设定聊天语句最长值

  注释4:设定浏览器显示的聊天语句行数

  注释5:这里加上15是为了将聊天的时间长度加进去

  注释6:文件过长就删除,再新建立一个

  注释7:以写的方式打开一个文件,如果该文件不存在就建立一个

  注释8:将聊天时间,聊天人,语句写到文件中

  最后:大家可以将本聊天室进行改造,加入房间,新建房间等等

责编:豆豆技术应用

正在加载评论...