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

PHP chat room application implementation method ideas

Dec 02, 2016 am 11:13 AM
php php chat room Implementation

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

//

// 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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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.

1

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

//

// 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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

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.

1

2

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.


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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles