Home > Backend Development > PHP Tutorial > PHP chat room application implementation method ideas

PHP chat room application implementation method ideas

伊谢尔伦
Release: 2023-03-02 21:10:01
Original
2265 people have browsed it

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:

PHP chat room application implementation method ideas

Enter the 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.

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

The PHP module receives form data from the 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.

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

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);
Copy after login

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.

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

In the chat_recv_ajax.php program, chat messages from users will be collected through the SQL select command. 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.

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;
Copy after login

When the data is ready, the JavaScript function will collect the data received from PHP. This data will be arranged within DIV tags. oxmlHttp.responseText will retain the chat message received from the PHP program and copy it to the document.getElementById("DIV_CHAT").innerHTML attribute of the DIV tag.

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;
    }
}
Copy after login

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));
Copy after login

Point of Interest

This code for implementing the 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.


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template