聊天室应用程序需要几个session共享数据的,但PHP没有象ASP那样有Application那样的组件的。现在给大家介绍一种用静态文件来共享数据的,只要每个用户提交发言,我们就用专门的程序把发言存到一个文本文件里,然后通过另一个页面来不时的读取它,再显示到客户机上的,基于此,我们需要三个PHP的程序,一个用来登录用的,一个用来刷新发言的,另一个用来客户提交发言的。我们先建个文件比如msg.txt,用它来存数据的。首先我们先看下登录的代码:
以下代码都经过测试能用的:
<!--login.php-->
<!--登录代码负责两个任务,一个看是否登录,假如有名字输入,就进入聊天室,当然大家可以修改它,使之界面更好点。-->
<?PHP
if(!$username)
{
echo "<html>";
echo "<body>";
echo "<br>";
echo "<br>";
echo "<hr>";
echo "<center>";
echo "<font color=blue><b>登陆聊天室无须密码</b></font>";
echo "</center>";
echo "<br>";
echo "<hr>";
echo "<center>";
echo "<form action=login.php method=POST>";
echo "您的呢称:<input type=text name=username><br>";
echo "您的密码:<input type=text name=mima><br>";
echo "........:<input type=submit value="进入"><br>";
echo "</form>";
echo "</body>";
echo "</html>";
}
else
{
if(!file_exists("msg.txt")){
$fp=fopen("msg.txt","w");
fputs($fp,"你是第一个到来");
fclose($fp);
}
$msg=file("msg.txt");
if(count($msg)>=10){
reset($msg);
next($msg);
}
$msg[]="聊天室宣布: <font color=blue><b>".$username."</b></font> 到来"."n";
$fp=fopen("msg.txt","w");
for(;list($line_num,$line)=each($msg);)
{
fputs($fp,$line,strlen($line));
}
fclose($fp);
echo "<html>";
echo "<frameset rows="*,100">";
echo "<frame src=message.php>";
echo "<frame src="chat.php?username=$username&mima=$mima">";
echo "</frameset>";
echo "</html>";
}
?>
现在再看下刷新用户的聊天代码:
<!--message.php-->
<!--四秒刷新一次-->
<html>
<head>
<meta http-equiv="Refresh" content="4">
</head>
<body>
<?php
$msg=file("msg.txt");
for(;list($line_num,$line)=each($msg);){
echo $line."<br>";
}
?>
</body>
</html>
下面是最重要的提交发言的代码:
<!--chat.php -->
<!-- 最多存十个发言记录-->
<html>
<body>
<?PHP
if($message){
$msg=file("msg.txt");
if(count($msg)>=10)
{
reset($msg);
next($msg);
}
$msg[]="<font color=green>".$username."</font>"."<font color=blue><b>说:</b></font>".$message."n";
$fp=fopen("msg.txt","w");
for(;list($line_num,$line)=each($msg);)
{
fputs($fp,$line,strlen($line));
}
fclose($fp);
}
?>
<form action=chat.php method=post>
<?PHP
echo "<input type=hidden value=$username name="username">";
echo "<input type=hidden value=$mima name="mima">";
echo "发言:<input type=text size=50 name=message>";
echo "<input type=submit value="发言">";
?>
</form>
</body>
</html>
哈!这就是聊天室了!当然这个聊天实在太粗糙了!没有一点活力,但是这个任务就交给聪明的读者来美化了!以上的代码均通过测试的! |