PHP聊天室應(yīng)用實(shí)現(xiàn)方法思路
聊天應(yīng)用程序在網(wǎng)上非常常見(jiàn)。開(kāi)發(fā)人員在構(gòu)建這類(lèi)應(yīng)用程序時(shí)的選擇也很多。這篇文章介紹了如何實(shí)現(xiàn)基于PHP-AJAX的聊天應(yīng)用程序,并且不需要刷新頁(yè)面就可以發(fā)送和接收消息。
核心邏輯在定義應(yīng)用程序的核心功能之前,先來(lái)看一看聊天應(yīng)用程序的基本外觀(guān),如以下截圖所示:

通過(guò)聊天窗口底部的輸入框輸入聊天文本。點(diǎn)擊Send按鈕,就開(kāi)始執(zhí)行函數(shù)set_chat_msg。這是一個(gè)基于Ajax的函數(shù),因此無(wú)需刷新頁(yè)面就可以將聊天文本發(fā)送到服務(wù)器。程序在服務(wù)器中執(zhí)行chat_send_ajax.php以及用戶(hù)名和聊天文本。
//// 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(查詢(xún)字符串)中接收表單數(shù)據(jù),更新到命名為chat的數(shù)據(jù)庫(kù)表中。chat數(shù)據(jù)庫(kù)表有命名為ID、USERNAME、CHATDATE和MSG的列。ID字段是自動(dòng)遞增字段,所以這個(gè)ID字段的賦值將自動(dòng)遞增。當(dāng)前的日期和時(shí)間,會(huì)更新到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();}
為了接收來(lái)自數(shù)據(jù)庫(kù)表中所有用戶(hù)的聊天消息,timer函數(shù)被設(shè)置為循環(huán)5秒調(diào)用以下的JavaScript命令,即每隔5秒時(shí)間執(zhí)行g(shù)et_chat_msg函數(shù)。
var t = setInterval(function(){get_chat_msg()},5000);
get_chat_msg是一個(gè)基于Ajax的函數(shù)。它執(zhí)行chat_recv_ajax.php程序以獲得來(lái)自于數(shù)據(jù)庫(kù)表的聊天信息。在onreadystatechange屬性中,另一個(gè)JavaScript 函數(shù)get_chat_msg_result被連接起來(lái)。在返回來(lái)自于數(shù)據(jù)庫(kù)表中的聊天消息的同時(shí),程序控制進(jìn)入到get_chat_msg_result函數(shù)。
//// 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程序中,來(lái)自于用戶(hù)的聊天消息會(huì)通過(guò)SQL select命令進(jìn)行收集。為了限制行數(shù),在SQL查詢(xún)中還給出了限制子句(limit 200),即要求聊天數(shù)據(jù)庫(kù)表中的最后200行。所獲得的消息再返回給Ajax函數(shù),用于在聊天窗口中顯示內(nèi)容。
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 . 'font-size: 10pt;' border='0'> <tbody><tr><td>' . $line['cdt'] . ' </td><td>' . $line['username'] . ': </td><td>' . $line['msg'] . '</td></tr></tbody></table>';echo $msg;
數(shù)據(jù)準(zhǔn)備就緒的同時(shí),JavaScript函數(shù)會(huì)收集來(lái)自于PHP接收到的數(shù)據(jù)。這些數(shù)據(jù)將被安排置于DIV標(biāo)簽內(nèi)。oxmlHttp.responseText會(huì)保留從PHP程序接收到的聊天消息,并復(fù)制到DIV標(biāo)簽的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命令可用于創(chuàng)建名為chat的數(shù)據(jù)庫(kù)表。所有由用戶(hù)輸入的信息都會(huì)進(jìn)入到數(shù)據(jù)庫(kù)表中。
create table chat( id bigint AUTO_INCREMENT,username varchar(20), chatdate datetime,msg varchar(500), primary key(id));興趣點(diǎn)
這段用于實(shí)現(xiàn)聊天應(yīng)用程序的代碼非常有意思。它可以改進(jìn)成為一個(gè)完全成熟的HTTP聊天應(yīng)用程序。創(chuàng)建該應(yīng)用程序的邏輯也非常簡(jiǎn)單。即使是初學(xué)者理解起來(lái)也不會(huì)有任何困難。
許可證這篇文章,以及任何相關(guān)的源代碼和文件,都獲得了The Code Project Open License (CPOL)的許可。
相關(guān)文章:
1. Django如何實(shí)現(xiàn)防止XSS攻擊2. PHP驗(yàn)證碼工具-Securimage3. 如何用JS實(shí)現(xiàn)簡(jiǎn)單的數(shù)據(jù)監(jiān)聽(tīng)4. 編寫(xiě)更好的 Java 單元測(cè)試的 7 個(gè)技巧5. 解決SpringBoot返回結(jié)果如果為null或空值不顯示處理問(wèn)題6. 如何在vue3.0+中使用tinymce及實(shí)現(xiàn)多圖上傳文件上傳公式編輯功能7. intellij idea寫(xiě)Python教程8. 使用本機(jī)IIS?Express開(kāi)發(fā)Asp.Net?Core應(yīng)用圖文教程9. java中應(yīng)用Stack進(jìn)行算術(shù)運(yùn)算的操作10. 利用CSS制作3D動(dòng)畫(huà)

網(wǎng)公網(wǎng)安備