PHP實現最簡單的聊天室應用
介紹
聊天應用程式在網上非常常見。開發人員在構建這類應用程式時的選擇也很多。這篇文章介紹了如何?基於PHP-AJAX的聊天應用程式,並且不需要重新整理頁面就可以發送和接收訊息。
核心邏輯
在定義應用程式的核心功能之前,先來看一看聊天應用程式的基本外觀,如以下所示:
通過聊天視窗底部的輸入框輸入聊天文本。點擊Send按鈕,就開始執行函數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模組從Query String查詢字串)中接收表單資料,更新到命名為chat的資料庫表中。chat資料庫表有命名為ID、USERNAME、CHATDATE和MSG的列。ID欄位是自動遞增欄位,所以這個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();
- }
為了接收來自資料庫表中所有使用者的聊天訊息,timer函數被設定為迴圈5秒調用以下的JavaScript命令,即每隔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 200),即要求聊天資料庫表中的最後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 . "
- "font-size: 10pt;" border="0">
-
" . $line["cdt"] . - "
|
" . $line["username"] . - ":
|
" . $line["msg"] . - "
|
";
-
- 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聊天應用程式。建立該應用程式的邏輯也非常簡單。即使是初學者理解起來也不會有任何困難。
許可證
這篇文章,以及任何相關的原始碼和檔案,都獲得了The Code Project Open License (CPOL)的許可。
譯文連結:http://www.codeceo.com/article/php-chart-app.html
英文原文:Chat Application in PHP
http://www.bkjia.com/PHPjc/1027371.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1027371.htmlTechArticlePHP實現最簡單的聊天室應用 介紹 聊天應用程式在網上非常常見。開發人員在構建這類應用程式時的選擇也很多。這篇文章介紹了如何?...