Click here to Skip to main content
11,639,765 members (59,937 online)
Click here to Skip to main content

Chat Application in PHP

, 7 Sep 2013 CPOL 89.5K 8.1K 27
Rate this:
Please Sign up or sign in to vote.
Chat application in PHP

Introduction

Chat programs are common on the web these days. Now developers have a wider range of options when building chat programs. This article gets you a PHP-AJAX based chat application and it does not require page reloading for sending and receiving messages.

Core Logic

Before defining the core functions in the application, have a look at the basic appearance of the chat application, depicted in the following screenshot:

The chat text can be given in the input box provided at the bottom of the chat window. While clicking the Send button, it starts executing function set_chat_msg. It is an Ajax based function so that without refreshing the page, it can send the chat text to the server. In the server, it executes chat_send_ajax.php 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);
}

The PHP module receives the form data as Query String and updates to the database table named chat. The chat database table has the column names ID, USERNAME, CHATDATE and MSG. The ID field is an auto-increment field so that values to this ID field will be incremented automatically. Current date with time is updated in 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();
}

To receive the chat messages of all users from the database table, a timer function is set for 5 seconds using the following JavaScript command. This will execute get_chat_msg function in 5 seconds interval.

var t = setInterval(function(){get_chat_msg()},5000);

The get_chat_msg is an Ajax based function. It executes chat_recv_ajax.php program to get chat messages from the database table. In the onreadystatechange property, another JavaScript function get_chat_msg_result is connected. While getting back the chat messages from database table, the program control goes to 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);
}

In the chat_recv_ajax.php program, chat messages from users will be collected using the SQL select command. To limit the number of rows in the result, a limit clause is given in the SQL query (limit 200). This will request the last 200 rows from the chat database table. The messages obtained are sent back 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;

While the data is ready, the JavaScript function will collect the data received from the PHP. This data will be arranged inside a DIV tag. The oxmlHttp.responseText will hold the chat messages received from the PHP program and this will be copied to document.getElementById("DIV_CHAT").innerHTML property 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;
    }
}

The following SQL CREATE TABLE command can be used to create the database table named chat. All the messages that are typed by the users are going 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

It is an interesting piece of code for implementing chat application. It can be modified to develop a full fledged HTTP chat application. Simple programming logic is used in creating this application. Beginners will not face any difficulty to understand this code.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sunil Kumar P
Sunsoft Systems
India India
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralThanks Pin
Member 118163256-Jul-15 0:44
memberMember 118163256-Jul-15 0:44 
Questiondrop down list Pin
Member 1177452120-Jun-15 1:27
memberMember 1177452120-Jun-15 1:27 
Generalmy vote Pin
nikunj vaghasiya30-Mar-15 16:15
membernikunj vaghasiya30-Mar-15 16:15 
Questionhello Pin
Member 113564846-Jan-15 6:19
memberMember 113564846-Jan-15 6:19 
Generaldatabase Pin
Member 1103073129-Oct-14 22:51
memberMember 1103073129-Oct-14 22:51 
QuestionGM Pin
Member 1102766021-Aug-14 15:07
memberMember 1102766021-Aug-14 15:07 
Suggestiongood Pin
Member 1037185012-May-14 22:52
memberMember 1037185012-May-14 22:52 
Questionthanks Pin
CHITRAKSH 20109-Mar-14 8:00
memberCHITRAKSH 20109-Mar-14 8:00 
QuestionWow...Nice... :) :) :) Pin
Member 106172924-Mar-14 3:29
memberMember 106172924-Mar-14 3:29 
GeneralThanks a lot Pin
sumit_1231-Feb-14 0:32
membersumit_1231-Feb-14 0:32 
QuestionTime Pin
Member 1048178022-Dec-13 3:32
memberMember 1048178022-Dec-13 3:32 
QuestionChat application Pin
Member 1044938511-Dec-13 3:54
memberMember 1044938511-Dec-13 3:54 
AnswerRe: Chat application Pin
Member 1044938511-Dec-13 4:30
memberMember 1044938511-Dec-13 4:30 
QuestionImprovement. Send message with ENTER keypress on input box Pin
XabiAberasturi20-Nov-13 3:01
memberXabiAberasturi20-Nov-13 3:01 
GeneralMy vote of 3 Pin
LAXATECH7-Nov-13 7:25
memberLAXATECH7-Nov-13 7:25 
GeneralThank-sa-lot Pin
LAXATECH7-Nov-13 7:16
memberLAXATECH7-Nov-13 7:16 
QuestionDatabase question Pin
viral8106-Oct-13 15:00
memberviral8106-Oct-13 15:00 
GeneralMy vote of 5 Pin
Sunil Kumar19-Sep-13 9:22
memberSunil Kumar19-Sep-13 9:22 
GeneralMy vote of 1 Pin
Sunasara Imdadhusen19-Sep-13 1:33
memberSunasara Imdadhusen19-Sep-13 1:33 
GeneralRe: My vote of 1 Pin
Sunil Kumar P19-Sep-13 8:40
memberSunil Kumar P19-Sep-13 8:40 
GeneralMy vote of 5 Pin
Member 432084416-Sep-13 6:05
memberMember 432084416-Sep-13 6:05 
GeneralMy vote of 5 Pin
daisy donald15-Sep-13 0:56
memberdaisy donald15-Sep-13 0:56 
GeneralMy vote of 5 Pin
Sally Joyce13-Sep-13 7:32
memberSally Joyce13-Sep-13 7:32 
GeneralMy vote of 5 Pin
aida doroja13-Sep-13 5:42
memberaida doroja13-Sep-13 5:42 
GeneralMy vote of 5 Pin
Dora Angelena12-Sep-13 19:58
memberDora Angelena12-Sep-13 19:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150731.1 | Last Updated 7 Sep 2013
Article Copyright 2013 by Sunil Kumar P
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid