Friday, 24 July 2009 06:36

In this tutorial we will be creating a simple web-based chat application with PHP and jQuery. This sort of utility would be perfect for a live support system for your website.
The chat application we will be building today will be quite simple. It will include a login and logout system, AJAX-style features, and will also offer support for multiple users.
We will start this tutorial by creating our first file called index.php.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Chat - Customer Module</title>
<link type="text/css" rel="stylesheet" href="style.css" />
</head>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b></b></p>
<p class="logout"><a id="exit" href="#">Exit Chat</a></p>
<div style="clear:both"></div>
</div>
<div id="chatbox"></div>
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" size="63" />
<input name="submitmsg" type="submit" id="submitmsg" value="Send" />
</form>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
// jQuery Document
$(document).ready(function(){
});
</script>
</body>
</html>
We will now add some css to make our chat application look better than with the default browser styling. The code below will be added to our style.css file.
/* CSS Document */
body {
font:12px arial;
color: #222;
text-align:center;
padding:35px; }
form, p, span {
margin:0;
padding:0; }
input { font:12px arial; }
a {
color:#0000FF;
text-decoration:none; }
a:hover { text-decoration:underline; }
#wrapper, #loginform {
margin:0 auto;
padding-bottom:25px;
background:#EBF4FB;
width:504px;
border:1px solid #ACD8F0; }
#loginform { padding-top:18px; }
#loginform p { margin: 5px; }
#chatbox {
text-align:left;
margin:0 auto;
margin-bottom:25px;
padding:10px;
background:#fff;
height:270px;
width:430px;
border:1px solid #ACD8F0;
overflow:auto; }
#usermsg {
width:395px;
border:1px solid #ACD8F0; }
#submit { width: 60px; }
.error { color: #ff0000; }
#menu { padding:12.5px 25px 12.5px 25px; }
.welcome { float:left; }
.logout { float:right; }
.msgln { margin:0 0 2px 0; }
There’s nothing special about the above css other than the fact that some id’s or classes, which we have set a style for, will be added a bit later.

As you can see above, we are finished building the chat’s user interface.
Now we will implement a simple form that will ask the user their name before continuing further on.
<?
session_start();
function loginForm(){
echo'
<div id="loginform">
<form action="index.php" method="post">
<p>Please enter your name to continue:</p>
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
<input type="submit" name="enter" id="enter" value="Enter" />
</form>
</div>
';
}
if(isset($_POST['enter'])){
if($_POST['name'] != ""){
$_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name']));
}
else{
echo '<span class="error">Please type in a name</span>';
}
}
?>
The loginForm() function we created is composed of a simple login form which asks the user for his/her name. We then use an if and else statement to verify that the person entered a name. If the person entered a name, we set that name as $_SESSION['name']. Since we are using a cookie-based session to store the name, we must call session_start() before anything is outputted to the browser.
One thing that you may want to pay close attention to, is that we have used the htmlspecialchars() function, which converts special characters to HTML entities, therefore protecting the name variable from become victim to Cross-site scripting (XSS). We will later also add this function to the text variable that will be posted to the chat log.
In order to show the login form in case a user has not logged in, and hence has not created a session, we use another if and else statement around the #wrapper div and script tags in our original code. On the opposite case, this will hide the login form, and show the chat box if the user is logged in and has created a session.;
<?php
if(!isset($_SESSION['name'])){
loginForm();
}
else{
?>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b><?php echo $_SESSION['name']; ?></b></p>
<p class="logout"><a id="exit" href="#">Exit Chat</a></p>
<div style="clear:both"></div>
</div>
<div id="chatbox"></div>
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" size="63" />
<input name="submitmsg" type="submit" id="submitmsg" value="Send" />
</form>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
// jQuery Document
$(document).ready(function(){
});
</script>
<?php
}
?>

We are not yet finished creating the login system for this chat application. We still need to allow the user to log out, and end the chat session. If you can remember, our original HTML markup included a simple menu. Let’s go back and add some PHP code that will give the menu more functionality.
First of all, let’s add the users name to the welcome message. We do this by outputting the session of the user’s name.
<p class="welcome">Welcome, <b><?php echo $_SESSION['name']; ?></b></p>

In order to allow the user to log out and end the session, we will jump ahead of ourselves and briefly use jQuery.
<script type="text/javascript">
// jQuery Document
$(document).ready(function(){
//If user wants to end session
$("#exit").click(function(){
var exit = confirm("Are you sure you want to end the session?");
if(exit==true){window.location = 'index.php?logout=true';}
});
});
</script>
The jquery code above simple shows a confirmation alert if a user clicks the #exit link. If the user confirms the exit, therefore deciding to end the session, then we send them to index.php?logout=true. This simple creates a variable called logout with the value of true. We need to catch this variable with PHP:

if(isset($_GET['logout'])){
//Simple exit message
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln'><i>User ". $_SESSION['name'] ." has left the chat session.</i><br></div>");
fclose($fp);
session_destroy();
header("Location: index.php"); //Redirect the user
}
We now see if a get variable of ‘logout’ exists using the isset() function. If the variable has been passed via a url, such as the link mentioned above, we proceed to end the session of the user’s name.
Before destroying the user’s name session with the session_destroy() function, we want to write a simple exit message to the chat log. It will say that the user has left the chat session. We do this by using the fopen(), fwrite(), and fclose() functions to manipulate our log.html file, which as we will see later on, will be created as our chat log. Please note that we have added a class of ‘msgln’ to the div. We have already defined the css styling for this div.
After doing this, we destroy the session, and redirect the user to the same page where the login form will appear.
After a user submits our form, we want to grab his input and write it to our chat log. In order to do this, we must use jQuery and PHP to work synchronously on the client and server sides.
Almost everything we are going to do with jQuery in order to handle our data, will revolve around the jQuery post request.
//If user submits the form
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
Please not that the code above will go into our script tag, where we placed the jQuery logout code.
At the moment we have POST data being sent to the post.php file each time the user submits the form, and sends a new message. Our goal now is to grab this data, and write it into our chat log.
<?
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln'>(".date("g:i A").") <b>".$_SESSION['name']."</b>: ".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
}
?>
Lastly, we close our file handle using fclose().
Everything the user has posted is handled and posted using jQuery; it is written to the chat log with PHP. The only thing left to do is to display the updated chat log to the user.
In order to save ourselves some time, we will preload the chat log into the #chatbox div if it has any content.
<div id="chatbox"><?php
if(file_exists("log.html") && filesize("log.html") > 0){
$handle = fopen("log.html", "r");
$contents = fread($handle, filesize("log.html"));
fclose($handle);
echo $contents;
}
?></div>
We use a similar routine as we used the post.php file, except this time we are only reading and outputting the contents of the file.
The ajax request is the core of everything we are doing. This request not only allows us to send and receive data throught the form without refreshing the page, but it also allows us to handle the data requested.
//Load the file containing the chat log
function loadLog(){
$.ajax({
url: "log.html",
cache: false,
success: function(html){
$("#chatbox").html(html); //Insert chat log into the #chatbox div
},
});
}
We wrap our ajax request inside a function. You will see why in a second. As you see above we will only use three of the jQuery ajax request objects.
As you see, we then move the data we requested (html) into the #chatbox div.
As you may have seen in other chat applications, the content automatically scrolls down if the chat log container (#chatbox) overflows. We are going to implement a simple and similar feature, that will compare the container’s scroll height before and after we do the ajax request. If the scroll height is greater after the request, we will use jQuery’s animate effect to scroll the #chatbox div.
//Load the file containing the chat log
function loadLog(){
var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20; //Scroll height before the request
$.ajax({
url: "log.html",
cache: false,
success: function(html){
$("#chatbox").html(html); //Insert chat log into the #chatbox div
//Auto-scroll
var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20; //Scroll height after the request
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}
},
});
}
Now one question may arise, how will we constantly update the new data being sent back and forth between users? Or to rephrase the question, how will we continuously keep sending requests to update the data?
setInterval (loadLog, 2500); //Reload file every 2500 ms or x ms if you wish to change the second parameter
The answer to our question lies in the setInterval function. This function will run our loadLog() function every 2.5 seconds, and the loadLog function will request the updated file and autoscroll the div.

We are finished! I hope that you learned how a basic chat system works, and if you have any suggestions on anything, I’ll happily welcome them. This chat system is a simple as you can get with a chat application. You can work off this and build a multiple chat rooms, add an administrative backend, add emoticons, ect. The sky here is your limit.
Below are a few links you might want to check if you are thinking of expanding this chat application:
