PHP实现聊天应用

原文地址:http://www.codeproject.com/Articles/649771/Chat-Application-in-PHP

Introduction

Chat programs are common on the web these days. Now developers have a wider range of options when building chat programs. This article gets you a PHP-AJAX based chat application and it does not require page reloading for sending and receiving messages.

聊天应用程序在当下非常普遍。现在开发者在构建聊天应用时又多了一种选择。这篇文件介绍了一种基于PHP ajax的聊天应用,它不需要页面重载来进行聊天信息的收发。

Core Logic

Before defining the core functions in the application, have a look at the basic appearance of the chat application, depicted in the following screenshot:

在定义这个应用的核心功能之前,我们来看一下这个应用的界面,如下图:

The chat text can be given in the input box provided at the bottom of the chat window. While clicking the Send button, it starts executing function set_chat_msg. It is an Ajax based function so that without refreshing the page, it can send the chat text to the server. In the server, it executes chat_send_ajax.php along with the username and chat text.

聊天信息在聊天窗口底部的信息输入框显示。当点击Send按钮的时候,程序开始执行set_chat_msg函数。它是一个基于ajax的函数因此不需要页面刷新,并且将聊天信息发送到服务端。在服务端chat_send_ajax.php会接收到username和聊天信息并执行。

//
// 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);
}

The PHP module receives the form data as Query String and updates to the database table named chat. Thechat database table has the column names IDUSERNAMECHATDATE and MSG. The ID field is an auto-increment field so that values to this ID field will be incremented automatically. Current date with time is updated in the CHATDATE column.

创建数据库webtech,然后执行下面脚本创建数据表。

CREATE TABLE `chat` (
  `ID` int(10) NOT NULL AUTO_INCREMENT,
  `USERNAME` varchar(64) DEFAULT NULL,
  `CHATDATE` datetime DEFAULT NULL,
  `MSG` varchar(1024) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

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();
}

To receive the chat messages of all users from the database table, a timer function is set for 5 seconds using the following JavaScript command. This will execute get_chat_msg function in 5 seconds interval.

var t = setInterval(function(){get_chat_msg()},5000);

The get_chat_msg is an Ajax based function. It executes chat_recv_ajax.php program to get chat messages from the database table. In the onreadystatechange property, another JavaScript function get_chat_msg_resultis connected. While getting back the chat messages from database table, the program control goes to theget_chat_msg_result function.

//
// 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);
}

In the chat_recv_ajax.php program, chat messages from users will be collected using the SQL select command. To limit the number of rows in the result, a limit clause is given in the SQL query (limit 200). This will request the last 200 rows from the chat database table. The messages obtained are sent back to the Ajax function for displaying the content in the chat window.

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;

While the data is ready, the JavaScript function will collect the data received from the PHP. This data will be arranged inside a DIV tag. The oxmlHttp.responseText will hold the chat messages received from the PHPprogram and this will be copied to document.getElementById("DIV_CHAT").innerHTML property of the DIVtag.

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;
    }
}

The following SQL CREATE TABLE command can be used to create the database table named chat. All the messages that are typed by the users are going into the database table.

create table chat( id bigint AUTO_INCREMENT,username varchar(20), 
chatdate datetime,msg varchar(500), primary key(id));

Points of Interest

It is an interesting piece of code for implementing chat application. It can be modified to develop a full fledged HTTP chat application. Simple programming logic is used in creating this application. Beginners will not face any difficulty to understand this code.


demo运行说明:

1、从原文地址下载代码

2、将代码放到本地web部署目录下

3、创建数据库webtech,并执行文中sql脚本创建数据表

4、修改db_connect.php中数据库连接参数

5、访问网址,例如:http://localhost/chat/chat.html就可以在网页上愉快地和自己聊天了~@~

如果聊天窗口无法显示内容,请将chat_recv_ajax.php内容修改如下:

<?php

     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="<table border='0' style='font-size: 10pt; color: blue; font-family: verdana, arial;'>";
     while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
     {
           $msg = $msg . "<tr><td>" . $line["CHATDATE"] . " </td>" .
                "<td>" . $line["USERNAME"] . ": </td>" .
                "<td>" . $line["MSG"] . "</td></tr>";
     }
     $msg=$msg . "</table>";
     
     echo $msg;

?>


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值