search
HomeBackend DevelopmentPHP TutorialPHP implements the simplest chat room application_PHP tutorial

PHP implements the simplest chat room application

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(&ldquo;DIV_CHAT&rdquo;).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



www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1027371.htmlTechArticleThe simplest chat room application implemented in PHP Introduction Chat applications are very common on the Internet. Developers also have many options when building such applications. This article explains how to achieve...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to calculate the total number of elements in a PHP multidimensional array?How to calculate the total number of elements in a PHP multidimensional array?May 15, 2025 pm 09:00 PM

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

What are the characteristics of do-while loops in PHP?What are the characteristics of do-while loops in PHP?May 15, 2025 pm 08:57 PM

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

How to hash strings in PHP?How to hash strings in PHP?May 15, 2025 pm 08:54 PM

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.

How to implement array sliding window in PHP?How to implement array sliding window in PHP?May 15, 2025 pm 08:51 PM

Implementing an array sliding window in PHP can be done by functions slideWindow and slideWindowAverage. 1. Use the slideWindow function to split an array into a fixed-size subarray. 2. Use the slideWindowAverage function to calculate the average value in each window. 3. For real-time data streams, asynchronous processing and outlier detection can be used using ReactPHP.

How to use the __clone method in PHP?How to use the __clone method in PHP?May 15, 2025 pm 08:48 PM

The __clone method in PHP is used to perform custom operations when object cloning. When cloning an object using the clone keyword, if the object has a __clone method, the method will be automatically called, allowing customized processing during the cloning process, such as resetting the reference type attribute to ensure the independence of the cloned object.

How to use goto statements in PHP?How to use goto statements in PHP?May 15, 2025 pm 08:45 PM

In PHP, goto statements are used to unconditionally jump to specific tags in the program. 1) It can simplify the processing of complex nested loops or conditional statements, but 2) Using goto may make the code difficult to understand and maintain, and 3) It is recommended to give priority to the use of structured control statements. Overall, goto should be used with caution and best practices are followed to ensure the readability and maintainability of the code.

How to implement data statistics in PHP?How to implement data statistics in PHP?May 15, 2025 pm 08:42 PM

In PHP, data statistics can be achieved by using built-in functions, custom functions, and third-party libraries. 1) Use built-in functions such as array_sum() and count() to perform basic statistics. 2) Write custom functions to calculate complex statistics such as medians. 3) Use the PHP-ML library to perform advanced statistical analysis. Through these methods, data statistics can be performed efficiently.

How to use anonymous functions in PHP?How to use anonymous functions in PHP?May 15, 2025 pm 08:39 PM

Yes, anonymous functions in PHP refer to functions without names. They can be passed as parameters to other functions and as return values ​​of functions, making the code more flexible and efficient. When using anonymous functions, you need to pay attention to scope and performance issues.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment