Home >Backend Development >PHP Tutorial >PHP implements the simplest chat room application_PHP tutorial
Introduction
Chat apps are very common online. Developers also have many options when building such applications. This article describes how to implement a PHP-AJAX based chat application that can send and receive messages without refreshing the page.
Core logic
Before defining the core functionality of the application, let’s take a look at the basic appearance of the chat application, as shown in the following screenshot:
Enter chat text through the input box at the bottom of the chat window. Click the Send button to start executing the function set_chat_msg. This is an Ajax based function so the chat text can be sent to the server without refreshing the page. The program executes chat_send_ajax.php in the server along with the username and chat text.
<ol class="dp-j"><li class="alt"><span><span class="comment">//</span><span> </span></span></li><li><span><span class="comment">// Set Chat Message</span><span> </span></span></li><li class="alt"><span><span class="comment">//</span><span> </span></span></li><li><span> </span></li><li class="alt"><span>function set_chat_msg() </span></li><li><span>{ </span></li><li class="alt"><span> <span class="keyword">if</span><span>(typeof XMLHttpRequest != </span><span class="string">"undefined"</span><span>) </span></span></li><li><span> { </span></li><li class="alt"><span> oxmlHttpSend = <span class="keyword">new</span><span> XMLHttpRequest(); </span></span></li><li><span> } </span></li><li class="alt"><span> <span class="keyword">else</span><span> </span><span class="keyword">if</span><span> (window.ActiveXObject) </span></span></li><li><span> { </span></li><li class="alt"><span> oxmlHttpSend = <span class="keyword">new</span><span> ActiveXObject(</span><span class="string">"Microsoft.XMLHttp"</span><span>); </span></span></li><li><span> } </span></li><li class="alt"><span> <span class="keyword">if</span><span>(oxmlHttpSend == </span><span class="keyword">null</span><span>) </span></span></li><li><span> { </span></li><li class="alt"><span> alert(<span class="string">"Browser does not support XML Http Request"</span><span>); </span></span></li><li><span> <span class="keyword">return</span><span>; </span></span></li><li class="alt"><span> } </span></li><li><span> </span></li><li class="alt"><span> var url = <span class="string">"chat_send_ajax.php"</span><span>; </span></span></li><li><span> var strname=<span class="string">"noname"</span><span>; </span></span></li><li class="alt"><span> var strmsg=<span class="string">""</span><span>; </span></span></li><li><span> <span class="keyword">if</span><span> (document.getElementById(</span><span class="string">"txtname"</span><span>) != </span><span class="keyword">null</span><span>) </span></span></li><li class="alt"><span> { </span></li><li><span> strname = document.getElementById(<span class="string">"txtname"</span><span>).value; </span></span></li><li class="alt"><span> document.getElementById(<span class="string">"txtname"</span><span>).readOnly=</span><span class="keyword">true</span><span>; </span></span></li><li><span> } </span></li><li class="alt"><span> <span class="keyword">if</span><span> (document.getElementById(</span><span class="string">"txtmsg"</span><span>) != </span><span class="keyword">null</span><span>) </span></span></li><li><span> { </span></li><li class="alt"><span> strmsg = document.getElementById(<span class="string">"txtmsg"</span><span>).value; </span></span></li><li><span> document.getElementById(<span class="string">"txtmsg"</span><span>).value = </span><span class="string">""</span><span>; </span></span></li><li class="alt"><span> } </span></li><li><span> </span></li><li class="alt"><span> url += <span class="string">"?name="</span><span> + strname + </span><span class="string">"&msg="</span><span> + strmsg; </span></span></li><li><span> oxmlHttpSend.open(<span class="string">"GET"</span><span>,url,</span><span class="keyword">true</span><span>); </span></span></li><li class="alt"><span> oxmlHttpSend.send(<span class="keyword">null</span><span>); </span></span></li><li><span>} </span></li></ol>
The PHP module receives form data from Query String (query string) and updates it to the database table named chat. The chat database table has columns named ID
, USERNAME
, CHATDATE
, and MSG
. The ID field is an auto-incrementing field, so the value assigned to this ID field will be automatically incremented. The current date and time will be updated to the CHATDATE column.
<ol class="dp-j"><li class="alt"><span><span>require_once(</span><span class="string">'dbconnect.php'</span><span>); </span></span></li><li><span> </span></li><li class="alt"><span>db_connect(); </span></li><li><span> </span></li><li class="alt"><span>$msg = $_GET[<span class="string">"msg"</span><span>]; </span></span></li><li><span>$dt = date(<span class="string">"Y-m-d H:i:s"</span><span>); </span></span></li><li class="alt"><span>$user = $_GET[<span class="string">"name"</span><span>]; </span></span></li><li><span> </span></li><li class="alt"><span>$sql=<span class="string">"INSERT INTO chat(USERNAME,CHATDATE,MSG) "</span><span> . </span></span></li><li><span> <span class="string">"values("</span><span> . quote($user) . </span><span class="string">","</span><span> . </span></span></li><li class="alt"><span> quote($dt) . <span class="string">","</span><span> . quote($msg) . </span><span class="string">");"</span><span>; </span></span></li><li><span> </span></li><li class="alt"><span> echo $sql; </span></li><li><span> </span></li><li class="alt"><span>$result = mysql_query($sql); </span></li><li><span><span class="keyword">if</span><span>(!$result) </span></span></li><li class="alt"><span>{ </span></li><li><span> <span class="keyword">throw</span><span> </span><span class="keyword">new</span><span> Exception(</span><span class="string">'Query failed: '</span><span> . mysql_error()); </span></span></li><li class="alt"><span> exit(); </span></li><li><span>} </span></li></ol>
In order to receive chat messages from all users in the database table, the timer function is set to loop for 5 seconds and call the following JavaScript command, that is, the get_chat_msg function is executed every 5 seconds.
var t = setInterval(function(){get_chat_msg()},5000);
get_chat_msg is an Ajax-based function. It executes the chat_recv_ajax.php program to obtain the chat information from the database table. In the onreadystatechange attribute, another JavaScript function get_chat_msg_result is connected. While returning the chat message from the database table, program control enters the get_chat_msg_result function.
<ol class="dp-j"><li class="alt"><span><span class="comment">//</span><span> </span></span></li><li><span><span class="comment">// General Ajax Call</span><span> </span></span></li><li class="alt"><span><span class="comment">//</span><span> </span></span></li><li><span> </span></li><li class="alt"><span>var oxmlHttp; </span></li><li><span>var oxmlHttpSend; </span></li><li class="alt"><span> </span></li><li><span>function get_chat_msg() </span></li><li class="alt"><span>{ </span></li><li><span> <span class="keyword">if</span><span>(typeof XMLHttpRequest != </span><span class="string">"undefined"</span><span>) </span></span></li><li class="alt"><span> { </span></li><li><span> oxmlHttp = <span class="keyword">new</span><span> XMLHttpRequest(); </span></span></li><li class="alt"><span> } </span></li><li><span> <span class="keyword">else</span><span> </span><span class="keyword">if</span><span> (window.ActiveXObject) </span></span></li><li class="alt"><span> { </span></li><li><span> oxmlHttp = <span class="keyword">new</span><span> ActiveXObject(</span><span class="string">"Microsoft.XMLHttp"</span><span>); </span></span></li><li class="alt"><span> } </span></li><li><span> <span class="keyword">if</span><span>(oxmlHttp == </span><span class="keyword">null</span><span>) </span></span></li><li class="alt"><span> { </span></li><li><span> alert(<span class="string">"Browser does not support XML Http Request"</span><span>); </span></span></li><li class="alt"><span> <span class="keyword">return</span><span>; </span></span></li><li><span> } </span></li><li class="alt"><span> </span></li><li><span> oxmlHttp.onreadystatechange = get_chat_msg_result; </span></li><li class="alt"><span> oxmlHttp.open(<span class="string">"GET"</span><span>,</span><span class="string">"chat_recv_ajax.php"</span><span>,</span><span class="keyword">true</span><span>); </span></span></li><li><span> oxmlHttp.send(<span class="keyword">null</span><span>); </span></span></li><li class="alt"><span>} </span></li></ol>
In the chat_recv_ajax.php program, chat messages from users will be collected through SQL select
commands. In order to limit the number of rows, a limit clause limit 200) is also given in the SQL query, which requires the last 200 rows in the chat database table. The obtained message is returned to the Ajax function for displaying the content in the chat window.
<ol class="dp-j"><li class="alt"><span><span>require_once(</span><span class="string">'dbconnect.php'</span><span>); </span></span></li><li><span> </span></li><li class="alt"><span>db_connect(); </span></li><li><span> </span></li><li class="alt"><span>$sql = "SELECT *, date_format(chatdate,<span class="string">'%d-%m-%Y %r'</span><span>) </span></span></li><li><span>as cdt from chat order by ID desc limit <span class="number">200</span><span>"; </span></span></li><li class="alt"><span>$sql = <span class="string">"SELECT * FROM ("</span><span> . $sql . </span><span class="string">") as ch order by ID"</span><span>; </span></span></li><li><span>$result = mysql_query($sql) or die(<span class="string">'Query failed: '</span><span> . mysql_error()); </span></span></li><li class="alt"><span> </span></li><li><span><span class="comment">// Update Row Information</span><span> </span></span></li><li class="alt"><span>$msg=<span class="string">""</span><span>; </span></span></li><li><span><span class="keyword">while</span><span> ($line = mysql_fetch_array($result, MYSQL_ASSOC)) </span></span></li><li class="alt"><span>{ </span></li><li><span> $msg = $msg . <span class="string">""</span><span> . </span></span></li><li class="alt"><span> <span class="string">""</span><span> . </span></span></li><li><span> <span class="string">""</span><span>; </span></span></li><li class="alt"><span>} </span></li><li><span>$msg=$msg . <span class="string">"<table style="</span><span>color: blue; font-family: verdana, arial; " . </span></span></li><li class="alt"><span> <span class="string">"font-size: 10pt;"</span><span> border=</span><span class="string">"0"</span><span>> </span></span></li><li><span> <tbody><tr><td><span class="string">" . $line["</span><span>cdt"] . </span></span></li><li class="alt"><span> <span class="string">" </td><td>"</span><span> . $line[</span><span class="string">"username"</span><span>] . </span></span></li><li><span> <span class="string">": </td><td>"</span><span> . $line[</span><span class="string">"msg"</span><span>] . </span></span></li><li class="alt"><span> <span class="string">"</td></tr></tbody></table>"</span><span>; </span></span></li><li><span> </span></li><li class="alt"><span>echo $msg; </span></li><li><span> </span></li><li class="alt"><span>数据准备就绪的同时,JavaScript函数会收集来自于PHP接收到的数据。这些数据将被安排置于DIV标签内。oxmlHttp.responseText会保留从PHP程序接收到的聊天消息,并复制到DIV标签的document.getElementById(“DIV_CHAT”).innerHTML属性。 </span></li><li><span> </span></li><li class="alt"><span>function get_chat_msg_result(t) </span></li><li><span>{ </span></li><li class="alt"><span> <span class="keyword">if</span><span>(oxmlHttp.readyState==</span><span class="number">4</span><span> || oxmlHttp.readyState==</span><span class="string">"complete"</span><span>) </span></span></li><li><span> { </span></li><li class="alt"><span> <span class="keyword">if</span><span> (document.getElementById(</span><span class="string">"DIV_CHAT"</span><span>) != </span><span class="keyword">null</span><span>) </span></span></li><li><span> { </span></li><li class="alt"><span> document.getElementById(<span class="string">"DIV_CHAT"</span><span>).innerHTML = oxmlHttp.responseText; </span></span></li><li><span> oxmlHttp = <span class="keyword">null</span><span>; </span></span></li><li class="alt"><span> } </span></li><li><span> var scrollDiv = document.getElementById(<span class="string">"DIV_CHAT"</span><span>); </span></span></li><li class="alt"><span> scrollDiv.scrollTop = scrollDiv.scrollHeight; </span></li><li><span> } </span></li><li class="alt"><span>} </span></li></ol>
The following SQL CREATE TABLE command can be used to create a database table named chat. All information entered by the user will be entered 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
This code for implementing a chat application is very interesting. It can be improved into a fully fledged HTTP chat application. The logic for creating this application is also very simple. Even beginners will not have any difficulty understanding it.
License
This article, and any related source code and files, are licensed under The Code Project Open License (CPOL).
Translation link: http://www.codeceo.com/article/php-chart-app.html
Original English text: Chat Application in PHP