How to Create A Simple Web-based Chat Application

How to Create A Simple Web-based Chat Application

Tutorial Details
  • Technologies: JavaScript,PHP,CSS
  • Difficulty: Beginner

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.


Introduction

final product

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.


Step 1 : HTML Markup

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 start our html with the usual DOCTYPE, html, head, and body tags. In the head tag, we add our title, and link to our css stylesheet (style.css).
  • Inside the body tag, we structure our layout inside the #wrapper div. We will have three main blocks: a simple Menu, our chatbox, and our message input; each with its respective div and id.
    • The #menu div will consist of two paragraph elements. The first will be a welcome to the user and will float left and the second will be an exit link and will float right. We also include a div to clear the elements.
    • The #chatbox div will contain our chatlog. We will load our log from an external file using jQuery’s ajax request.
    • The last item in our #wrapper div will be our form, which will include an text input for the user message and a submit button.
  • We add our scripts last to load the page faster. We will first link to the Google jQuery CDN, as we will be using the jQuery library for this tutorial. Our second script tag will be where we will be working on. We will load all of our code after the document is ready.

Step 2 : CSS Styling

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.

Step 3 : Using PHP to Create a Login Form.

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.

Showing the Login Form

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
}
?>

Welcome and Logout Menu

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.


Step 4 : Handling User Input

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.

jQuery

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;
	});
  1. Before we do anything, we must grab the user’s input, or what he has typed into the #submitmsg input. This can be achieved with the val() function, which gets the value set in a form field. We now store this value into the clientmsg variable.
  2. Here come’s our most important part: the jQuery post request. This sends a POST request to the post.php file that we will create in a moment. It posts the clients input, or what has been saved into the clientmsg variable.
  3. Lastly, we clear the #usermsg input by setting the value attribute to blank.

Please not that the code above will go into our script tag, where we placed the jQuery logout code.

PHP – post.php

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);
}
?>
  1. Before we do anything, we have to start the post.php file with the session_start() function as we will be using the session of the user’s name in this file.
  2. Using the isset boolean, we check if the session for ‘name’ exists before doing anything else.
  3. We now grab the POST data that was being sent to this file by jQuery. We store this data into the $text variable.
  4. This data, as will all overall user input data, will be stored on the log.html file. To do this we open the file with the mode on the fopen function to ‘a’, which according to php.net opens the file for writing only; places the file pointer at the end of the file. If the file does not exist, attempt to create it. We then write our message to the file using the fwrite() function.
    • The message we will be writing will be enclosed inside the .msgln div. It will contain the date and time generated by the date() function, the session of the user’s name, and the text, which is also sorrounded by the htmlspecialchars() function to prevent from XSS.

    Lastly, we close our file handle using fclose().


Step 5 : Displaying the Chat Log (log.html) Contents

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 jQuery.ajax request

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.

  • url: A string of the URL to request. We will use our chat log’s filename of log.html.
  • cache: This will prevent the our file from being cached. It will ensure that we get an updated chat log everytime we send a request.
  • sucess: This will allow us to attach a function that will pass the data we requested.

As you see, we then move the data we requested (html) into the #chatbox div.

Auto-scrolling

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
				}				
		  	},
		});
	}
  • We first store the #chatbox div’s scroll height into the oldscrollHeight variable before we make the request.
  • After our request has returned sucessful, we store the #chatbox div’s scrolle height into the newscrollHeight variable.
  • We then compare both of the scroll height variables using an if statement. If the newscrollHeight is greater than the oldscrollHeight, we use the animate effect to scroll the #chatbox div.

Continuously Updating the Chat Log

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.

Finished

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:


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://teknami.com IDS07

    Is there a way to add a chat filter or word replacement to this project?

  • Ben

    I have tried to follow this tutorial with no success. Your first example code is html but your downloaded code does not include an html document. I tried to take the downloaded code and run it on my web server and it does not present the pages. You get the enter you name box but nothing happens when you do. Also you see some of the code. I guess my question would be is the download code suppose to work. I have PHP and JQuery on my server.

  • Ben

    Got the page to display but now I get Invalid character in line 1 when I do anything. Has anyone else had this problem. I resolved my previous problem by correcting a code error for current PHP. <? chane to
    <?php.

  • http://nonan.ir/ Ali

    hello,

    good script, but it works not in IE7? how is it?

    • vali

      it’s good. It works fine, at least on localhost. Thanks for the code.

  • http://www.caustik.heliohost.org Adil

    Awesome chatbox, very easy to use.

    • Aryan

      I have no idea to build a website plz give me all information about that ..and where i use these code

  • Karthik

    can anyone tell me how to make this chat private…

  • http://zakylubismy.blogspot.com lubis

    mohon bantunnya.. mksh infonya

  • https://github.com/kstrauser/seshat Kirk Strauser

    I used this setup as inspiration for a web chat system, “Seshat”, that I wrote for the Pyramid web framework. Thanks for the great example!

  • http://myringbacktones.blogspot.com arthree

    good information for your info………

  • javinczki

    thanx! it helps

  • http://twitter.com/srabonHasan srabon

    it helps , thanks :)

  • http://www.chemia.umiej.pl Outslider

    Isn’t that good idea to add flock function in post.php? If two users will post message at the same moment, lock absence may couse problems…

  • http://www.icycoolgames.com/ IcyCoolGames

    How would I make this chat application to where my users can talk to each other privately? For instances, like hotmail or facebook chat.

  • http://aaa.aaa aaa

    great example for chat.
    Thanks
    aaa

  • acrocks

    hi, i got stuck!
    when i got to the part of creating the login form, where should i add the form or where and how should i save it?

    • Fumestine

      Hi acrocks
      i have the same problem. anyone help!!!!

  • http://asfa Tomashqooo

    How can I resize the login window????

  • http://www.industrijasrbije.rs Vladislav

    thanks :)

  • murtaza

    it is a wisely written post
    and well understood ..

    http://bit.ly/mlrzR1

    i have deployed the source ..

    thanks.

    • Guus

      Can you please send me the source files, because I get stuck at the form section. Thank you!

    • murtaza

      http://bit.ly/mlrzR1
      i have done some improvisation to have online / offline users.

  • smita

    how do i get other user with this code ?

  • Ayyaz

    Wow , Very interesting and explained with so easy steps, I really thank you very much for such a great effort. I did not tested this code yet , But I am going to test this and then will again come here to post feedback… :)

  • vince calone

    Can any one tell me how to ad a photo to a chat session? I was on one last night and someone kept showing pictures of their family right in the chat box while in session while we were talking???? it was nice. How hard or simple is this?
    Again not intersted in creating a new chat room or chat location ONLY how do I place or embed photo in a chat session.

    Vince

  • fq2007

    i`ve tried ths chat…its work on localhost ,but when i put in domain orgfree.com ,cht msg does`t wrk :( .. cn anyone hlp me..

  • http://seoexpertlahore.blogspot.com seo lahore

    Wow. Great list! I have used a lot of them before, but it is nice to have them all in one place. I really should go .

  • Tim

    Why doesn’t this work with Internet Explorer?

  • http://www.mohityagi.com mohit

    nice work.. it worked.

  • http://www.canseburesort.co.id amierphp

    i’ll install in my website :D

  • http://wdevelopers.info Wasim Amin

    Hello buddy i have tried to use your chat system but it is creating some problem for me …
    THe ajax function is not working for
    can you tell me that where to call the autoscrolling function

  • http://blog.sina.com.cn/ggsddunet zz2

    nice work, it’s so userful,

  • help

    how do you run the script? im not an expert at running scripts in dreamweaver but i made it just fine, just wanted to run it.

  • Baisha

    hello, thanks for the tutorial. I noticed its a one way chat..how do I connect someone else to chat with me? How do I implement it to my website?

  • http://howtooblogging.blogspot.com How To Blogging

    I have tried to follow this tutorial with no success. Your first example code is html but your downloaded code does not include an html document. I tried to take the downloaded code and run it on my web server and it does not present the pages. You get the enter you name box but nothing happens when you do. Also you see some of the code. I guess my question would be is the download code suppose to work. I have PHP and JQuery on my server, then at last i found this Blog.

  • get_slayeer

    its good n i make it properly with success but how i connect anyone else with me for chat with it,,its only one way chattinnng:S:S:S:S

  • hosein

    I think the “Continuously Updating…” paragraph is most important part of this post.
    ThanKs A Loo0o0oo0oT!

  • http://www.cellpathnigeria.com Christian

    Please the chat codes section was not given names,Please to make it clearer name every code your write so we can follow up easily,like index.php,ajax.js and the rest.

  • http://www.mobilemoot.com mobidea

    Yes this full work on my web…check this, may u can get backlink.

  • reenez

    nice tutorial

  • http://fu FUK_U

    he doesnt make it clear on what the individual files should be named, by design of course, to get you to PAY for hm to explain. and notice there’s dozens of “got it to work, great code” posts on here but my bet is it is all the author boasting his own code. in short, this is someone trying to run some kind of scam. fuck him. dont waste yr time, find someone willing to give full details in the instructions. a guy who can write this kind of code did not “accidentally” leave out the instructions on what you should name the individual files, or tell you whether all this code goes on one page, 2 pages, 3, 4, 5. He doesnt mention any of that. fuck him he’s a punk bitchhhhhhhhh running a nigga scam

    • vali

      dude, you’re so stupid. The code works fine. You are an idiot: ask questions if you don’t understand it(becouse you’re so stupid), don’t go swearing around, like an idiot, becouse everyone will find out what a idiot you are.

      • John

        Agreed – just another lazy, stupid internet low-life. I got this code to work fine too. Here are a couple of small improvements:

        1) So you can press enter (as well as clicking the button) without having the form default to the “get” method, begin the “message” form:

        <form name=”message” method=”post”>

        You also don’t need to put action=”".

        2) Add the following to refocus the textbox each time you enter text (after the attr() function):

        $(“#usermsg”).focus();

  • Sid

    Thanks for the post. Very useful. I’ve added a str_replace function for creating smileys in the post.php file.

  • LA

    Issue1: when I tried to view the index.php on my local server, the chatroom/login did not get displayed as it should.
    Issue2: Once I got that working, my posts would not show in the chatroom./////

    Solution:===> There are two areas where the php code started with <?. All i did was to change <? to <?php and the sample worked perfectly. ////One area is in the beginning of the file index.php file. (It starts with <? I changed it to <?php The other is in the post.php file. It also had <? in beginning I just changed it to <?php

    ////hope that helped some of you.

  • http://www.minime4u.com Mini me doll

    Nice one, thank you.

  • aakash

    I tried to use your code but it didnt work. As soon as I press submit button 404 error page not found is displayed. Any idea how to resolve it.

  • http://www.twitter.com/rosalindwills Rosalind Wills

    Great tutorial. Thanks!

    Can someone tell me…if I wanted to include a feature whereby the server could identify if the user was no longer connected to the chat (i assume by getting some sort of regular ping from the client side) and display the “User has left the chat” for other reasons than an official logout, how would I go about that?

  • Amit gupta

    hey can any one help i use this script what after login i m not able to chat or send the msg

  • http://forum.unpoo.com hasret

    very very nice. very good aplication. thanks my friend

  • Aryan

    I don’t know that whese i use these codes tell me plz

  • Aryan

    What is this software any one tell me for this i wanna made a chat site for my friends so plz tell me all about build a chat site plz plz plz

  • Learner

    Hey, Can someone either tell me the steps and where to save each code and under what file type, or could someone send me a simple example ( so the main strucutre with it working ) and then i will take it from there? thankyou that would be much help.

  • http://sidesi.co Fodor

    Hi.
    A great system. Very easy for dumb people (actually far too simple).
    Though it has one (terrible) drawback:
    It doesn’t use MySQL or any DB at all. Which makes it difficult for management.For example, I created a chat system for one website and I had to make it in a way that the moderators could delete messages and stop /ban/ spammers. It was very easy. Just by making a simple mysql check if the user is banned before sending the message I made the system to be easy to use by moderators. Also they can just click an delete link and delete a message. The messages are stored for about 10 minutes.
    And here it is a bit messy . All those simple things are (almost) removed, because it doesn’t use a DB. Great for newbies. Terrible for real implementation.

  • http://www.etrealamode.com/ Blog mode

    very very nice than’s you so much ;)

  • Iggy

    I want to know at what interval does “setInterval (loadLog, 2500);” become hard to hangle for the system?