PHP 中的聊天应用程序






4.76/5 (51投票s)
PHP 中的聊天应用程序
引言
如今,基于网络的聊天程序非常常见。现在,开发者在构建聊天程序时拥有更广泛的选择。本文将向您介绍一个基于PHP和AJAX的聊天应用程序,它不需要页面重新加载即可发送和接收消息。
核心逻辑
在定义应用程序的核心函数之前,请查看以下屏幕截图所示的聊天应用程序的基本外观

聊天文本可以在聊天窗口底部的输入框中输入。单击“发送”按钮时,它将开始执行函数set_chat_msg
。这是一个基于Ajax的函数,因此无需刷新页面,即可将聊天文本发送到服务器。在服务器上,它将与用户名和聊天文本一起执行chat_send_ajax.php。
//
// Set Chat Message
//
function set_chat_msg()
{
if(typeof XMLHttpRequest != "undefined")
{
oxmlHttpSend = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
oxmlHttpSend = new ActiveXObject("Microsoft.XMLHttp");
}
if(oxmlHttpSend == null)
{
alert("Browser does not support XML Http Request");
return;
}
var url = "chat_send_ajax.php";
var strname="noname";
var strmsg="";
if (document.getElementById("txtname") != null)
{
strname = document.getElementById("txtname").value;
document.getElementById("txtname").readOnly=true;
}
if (document.getElementById("txtmsg") != null)
{
strmsg = document.getElementById("txtmsg").value;
document.getElementById("txtmsg").value = "";
}
url += "?name=" + strname + "&msg=" + strmsg;
oxmlHttpSend.open("GET",url,true);
oxmlHttpSend.send(null);
}
PHP模块将表单数据作为查询字符串接收,并更新到名为chat
的数据库表中。chat
数据库表包含列名ID
、USERNAME
、CHATDATE
和MSG
。ID
字段是一个自动递增字段,因此该字段的值将自动递增。当前日期和时间将更新到CHATDATE
列中。
require_once('dbconnect.php');
db_connect();
$msg = $_GET["msg"];
$dt = date("Y-m-d H:i:s");
$user = $_GET["name"];
$sql="INSERT INTO chat(USERNAME,CHATDATE,MSG) " .
"values(" . quote($user) . "," .
quote($dt) . "," . quote($msg) . ");";
echo $sql;
$result = mysql_query($sql);
if(!$result)
{
throw new Exception('Query failed: ' . mysql_error());
exit();
}
要从数据库表中接收所有用户的聊天消息,使用以下JavaScript命令设置一个5秒的timer
函数。这将以5秒的间隔执行get_chat_msg
函数。
var t = setInterval(function(){get_chat_msg()},5000);
get_chat_msg
是一个基于Ajax的函数。它执行chat_recv_ajax.php程序以从数据库表中获取聊天消息。在onreadystatechange
属性中,连接了另一个JavaScript函数get_chat_msg_result
。在从数据库表获取聊天消息时,程序控制权将转到get_chat_msg_result
函数。
//
// General Ajax Call
//
var oxmlHttp;
var oxmlHttpSend;
function get_chat_msg()
{
if(typeof XMLHttpRequest != "undefined")
{
oxmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
oxmlHttp = new ActiveXObject("Microsoft.XMLHttp");
}
if(oxmlHttp == null)
{
alert("Browser does not support XML Http Request");
return;
}
oxmlHttp.onreadystatechange = get_chat_msg_result;
oxmlHttp.open("GET","chat_recv_ajax.php",true);
oxmlHttp.send(null);
}
在chat_recv_ajax.php程序中,将使用SQL select
命令收集用户的聊天消息。为了限制结果中的行数,SQL查询中给出了一个limit子句(limit 200)。这将从chat数据库表中请求最后200行。获得的消息将发送回Ajax函数,以便在聊天窗口中显示内容。
require_once('dbconnect.php');
db_connect();
$sql = "SELECT *, date_format(chatdate,'%d-%m-%Y %r')
as cdt from chat order by ID desc limit 200";
$sql = "SELECT * FROM (" . $sql . ") as ch order by ID";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
// Update Row Information
$msg="";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
{
$msg = $msg . "" .
"" .
"";
}
$msg=$msg . "<table style="color: blue; font-family: verdana, arial; " .
"font-size: 10pt;" border="0">
<tbody><tr><td>" . $line["cdt"] .
" </td><td>" . $line["username"] .
": </td><td>" . $line["msg"] .
"</td></tr></tbody></table>";
echo $msg;
当数据准备就绪时,JavaScript函数将收集从PHP接收到的数据。这些数据将被安排在DIV
标签内。oxmlHttp.responseText
将保存从PHP程序接收到的聊天消息,并将将其复制到DIV
标签的document.getElementById("DIV_CHAT").innerHTML
属性中。
function get_chat_msg_result(t)
{
if(oxmlHttp.readyState==4 || oxmlHttp.readyState=="complete")
{
if (document.getElementById("DIV_CHAT") != null)
{
document.getElementById("DIV_CHAT").innerHTML = oxmlHttp.responseText;
oxmlHttp = null;
}
var scrollDiv = document.getElementById("DIV_CHAT");
scrollDiv.scrollTop = scrollDiv.scrollHeight;
}
}
以下SQL CREATE TABLE
命令可用于创建名为chat
的数据库表。所有用户键入的消息都将进入数据库表。
create table chat( id bigint AUTO_INCREMENT,username varchar(20),
chatdate datetime,msg varchar(500), primary key(id));
关注点
这是一个实现聊天应用程序的有趣代码。它可以被修改以开发一个功能齐全的HTTP聊天应用程序。这种应用程序使用了简单的编程逻辑。初学者不会难以理解这段代码。