Friday, September 17, 2010

Simple Chat script in PHP, MySQL and Ajax

In this tutorial I will show you how to create a simple but very effective Chat script, and I said effective because unlike the most of the chat scripts this one deletes automatically the old messages from the database. Here is a live demo:

The chat is refreshed automatically each 30 seconds.

Let`s start: First we need to create a MySQL table with 4 fields:
time - the time when the message was posted (UNIX)
name - the name of the author of the message
ip - the ip of the author of the message
message - the message text
To create the table (I will call it chat) I`we used the following file:
create-table.php
<?php
//Connect to MySQL
mysql_connect('host', 'database', 'password')
or die (mysql_error());
//Select database
mysql_select_db('database')
or die (mysql_error());
//Create the table
mysql_query("create table chat(
time int(11) NOT NULL,
name varchar(30) NOT NULL,
ip varchar(15) NOT NULL,
message varchar(255) NOT NULL,
PRIMARY KEY (time)
)") or die (mysql_error());
echo "Complete.";
?>

For the rest of the Chat script we will need 3 more files:
chat.php
send.php
show-messages.php

Let`s start with the chat.php what will contain the forms and all the Ajax scripts what will trigger the other 2 files:
chat.php
<html>
<head>
<style>
.message {
overflow:hidden;
width:498px;
margin-bottom:5px;
border:1px solid #999;
}
.messagehead {
overflow:hidden;
background:#FFC;
width:500px;
}
.messagecontent {
overflow:hidden;
width:496px;
}
</style>
</head>

<body>
<div id="chat" style="width:500px;margin:0 auto;overflow:hidden;">
//This div will contain the messages
<div id="messages"></div>
//This div will contain an eventual error message
<div id="error" style="width:500px;text-align:center;color:red;"></div>
//This div contains the forms and the send button
<div id="write" style="text-align:center;"><textarea id="message" cols="50" rows="5"></textarea><br/>Name:<input type="text" id="name"/><input type="button" value="Send" onClick="send();"/></div>
</div>

<script type="text/javascript">
//This function will display the messages
function showmessages(){
//Send an XMLHttpRequest to the 'show-message.php' file
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","show-messages.php",false);
xmlhttp.send(null);
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET","showmessages.php",false);
xmlhttp.send();
}
//Replace the content of the messages with the response from the 'show-messages.php' file
document.getElementById('messages').innerHTML = xmlhttp.responseText;
//Repeat the function each 30 seconds
setTimeout('showmessages()',30000);
}
//Start the showmessages() function
showmessages();
//This function will submit the message
function send(){
//Send an XMLHttpRequest to the 'send.php' file with all the required informations
var sendto = 'send.php?message=' + document.getElementById('message').value + '&name=' + document.getElementById('name').value;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",sendto,false);
xmlhttp.send(null);
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET",sendto,false);
xmlhttp.send();
}
var error = '';
//If an error occurs the 'send.php' file send`s the number of the error and based on that number a message is displayed
switch(parseInt(xmlhttp.responseText)){
case 1:
error = 'The database is down!';
break;
case 2:
error = 'The database is down!';
break;
case 3:
error = 'Don`t forget the message!';
break;
case 4:
error = 'The message is too long!';
break;
case 5:
error = 'Don`t forget the name!';
break;
case 6:
error = 'The name is too long!';
break;
case 7:
error = 'This name is already used by somebody else!';
break;
case 8:
error = 'The database is down!';
}
if(error == ''){
document.getElementById('error').innerHTML = '';
showmessages();
}
else{
document.getElementById('error').innerHTML = error;
}
}
</script>

</body>
</html>

send.php
<?php
//Connect to MySQL
mysql_connect('host', 'database', 'password') or die (1);
//Select database
mysql_select_db('database') or die (2);
//Check if message is empty and send the error code
if(strlen($message) < 1){
echo 3;
}
//Check if message is too long
else if(strlen($message) > 255){
echo 4;
}
//Check if name is empty
else if(strlen($name) < 1){
echo 5;
}
//Check if name is too long
else if(strlen($name) > 29){
echo 6;
}
//Check if the name is used by somebody else
else if(mysql_num_rows(mysql_query("select * from chat where name = '" . $name . "' and ip != '" . @$REMOTE_ADDR . "'")) != 0){
echo 7;
}
//If everything is fine
else{
//This array contains the characters what will be removed from the message and name, because else somebody could send redirection script or links
$search = array("<",">","&gt;","&lt;");
//Insert a new row in the chat table
mysql_query("insert into chat values ('" . time() . "', '" . str_replace($search,"",$name) . "', '" . @$REMOTE_ADDR . "', '" . str_replace($search,"",$message) . "')") or die(8);
}
?>

show-messages.php
<?php
//Connect to MySQL
mysql_connect('host','database','password');
//Select database
mysql_select_db('database') or die(2);
//Get the first 10 messages ordered by time
$result = mysql_query("select * from chat order by time desc limit 0,10");
$messages = array();
//Loop and get in an array all the rows until there are not more to get
while($row = mysql_fetch_array($result)){
//Put the messages in divs and then in an array
$messages[] = "<div class='message'><div class='messagehead'>" . $row[name] . " - " . date('g:i A M, d Y',$row[time]) . "</div><div class='messagecontent'>" . $row[message] . "</div></div>";
//The last posts date
$old = $row[time];
}
//Display the messages in an ascending order, so the newest message will be at the bottom
for($i=9;$i>=0;$i--){
echo $messages[$i];
}
//This is the more important line, this deletes each message older then the 10th message ordered by time is deleted, so the table will never have to store more than 10 messages.
mysql_query("delete from chat where time < " . $old);
?>
And this is it. A very effect chat system what uses only 10 rows of a MySQL table. This chat system can be easily upgraded with admin options or IP bans, smileys and other stuff like this. If you have any question related to this chat system just ASK!

UPDATE: a new version of this script (that works in IE) is ready: Cross-browser chat

34 comments:

Anonymous said...

pretty awesome!

free to use / what's license?
can't seem to find a disclaimer on the site :)

thanks!

Csabi said...

It`s totally free to use, but a backlink is always good, although it`s not required.

Anonymous said...

Sweet tutorial! There's a tiny bug in send.php though, you need to add
$message = $_GET['message'];
$name = $_GET['name'];
at the top, to grab the values sent from chat.php. Otherwise, works great!

Csabi said...

I`we used another method instead:
The values are sent by URL parameters:
'send.php?message=' + document.getElementById('message').value + '&name=' + document.getElementById('name').value;

Anonymous said...

Try this; run your send.php script directly, and type in send.php?message=testing&name=something and then in send.php echo $message and $name, you'll see they return nothing(empty).

This is because you're not assigning the values via the $_GET first.

Csabi said...

OK, the reason because it returns nothing is that if the message was successfully sent then send.php returns nothing (check the source-code).

I`we tried to run the send.php file directly and it worked, the message is displayed in the chat window: by something : testing

Another reason may be that the send.php file is not uploaded to this website, the full URL is:
http://coolboycsaba.freehostia.com/chat/send.php?message=testing&name=something

Anonymous said...

Wow this is awesome, it really helps thanks

e11world said...

Pretty neat system!

Anonymous said...

Dear Csabi,
I have try it but get
" Don`t forget the message" . I am new in PHP,HTML
Need your help.

Csabi said...

Don`t leave blank the message textarea
If it will don`t work than contact me again

Isabanur said...

hi i've tried the script and its sending the data to the database but its not outputting to the page

can u help me??
thanks

Csabi said...

Than probably the problem is with the javascript part.

Try to alert() the xmlhttp.responseText in the following way (inside the showmessages() function):
alert(xmlhttp.responseText);

and see what is alerted

Anonymous said...

@Anonymous & @Csabi
The direct use of $message, instead of $_GET['message'] works because the old version of PHP create automatically the corresponding variable.

Anonymous said...

Why I'm getting the message "Don't forget the message!" although i've wrote a message? has the script a problem with IE? Thx for answering me.
Great job

Csabi said...

I`we downloaded the latest IE and I`we tested it. The message was sent without showing any error but it doesn`t refresh, not even when I`we pressed the Send button.

Csabi said...

What version of IE are you using ?
Did you test the script in another browser, too ?

Anonymous said...

HI
First i will say thanks to the author.
I need ur help this is not working in IE y . Pls Help me boss
Thanks
Ur friend

r said...

hi thanks but this script is not working in IE please help me

Csabi said...

I`we fixed the IE problems, here is the new script: Cross-browser chat script

Anonymous said...

I saw above that someone else had this problem, I get the values in my tables, but nothing sends back. I tried the alert but that's returning back empty. Any suggestions? Thanks for any help you can give :D

Csabi said...

Please send me the URL of your script

Anonymous said...

Hi, thanks for the script, but i don't get the values in my tables and there is not output in the page, why?? I use IE 7. Help me!

Csabi said...

Add $message = $_GET['message'];
$name = $_GET['name'];
to the beginning of your send.php

Anonymous said...

Hi, thanks for this script but what i have to fill in mysql_connect('host', 'database', 'password') or die (1); sry im a newbie : /
An example would be nice : )

Csabi said...

host: the host is somehow the url of your mysql, if you are using it from your PC then usually it`s localhost
database: your mysql username
password: you password

Anonymous said...

Essential change to get this to work in Chrome:
Add
$message = $_GET['message'];
$name = $_GET['name'];
to the beginning of your send.php

Csabi said...

Yes, this depends on you PHP version

Anonymous said...

hi i have used this script, but when i type message and name in chat.php and then click on send button, nothing happens, please help me out

Anonymous said...

Hi ! i liked this!
but im looking for a solution for creating some support chat (live support chat ) system!
can you help me??

Anonymous said...

!! Great people still exist !!
. . Nice work . .
lykd ur "i'we" part . . :D

ravenjojo said...

kindly give the code if you are using a login and logout system...instead of typing name...it automatically post the name that you login, tnx!
pls send it to my email coz it is a group project..jojo_fernandez38@yahoo.com

Anonymous said...

Great!!!!!

Anonymous said...

great application

Anonymous said...

It is indeed a great tips. With that I could extend the functionalities to suit my need. But the send text field is never cleared after sending a data. I am new in Php so have now idea.

Post a Comment

 
Powered by Blogger