Wednesday, December 22, 2010

Private chat room script

Finally my private chat room is ready! I`we used jQuery, PHP and 2 MySQL tables to write this script. This is the first version, this is some kind of beta version, because I hadn`t test it yet, because it needs at least 2 users to work... Here is a live demo, have fun with it and please tell me about the errors:
NOTES:
Everything is refreshed each 15 seconds.
An user is logged out after 10 minutes of inactivity.
Each message is kept for 30 minutes.
An users name is highlighted with orange if the user sent you a message.
The selected username is highlighted with red.

As I said, we will need two mysql tables: one to hold the users (username, ip, last activity date) and one for the messages (from, to, message, date). Here is my code to create the tables:
table1.php
<?php
mysql_connect("host", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
mysql_query("CREATE TABLE chatusers(
username VARCHAR(30),
ip CHAR(15),
lastactive INT UNSIGNED,
PRIMARY KEY(username)
)")
or die(mysql_error());
echo "Table Created!";
?>
table2.php
<?php
mysql_connect("host", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
mysql_query("CREATE TABLE messages(
messagefrom VARCHAR(30),
sendto VARCHAR(30),
message VARCHAR(255),
date INT UNSIGNED
)")
or die(mysql_error());
echo "Table Created!";
?>

It`s hard to explain how it works... but I will try to. At the start if your ip is not in the database you will be asked for an username and you will be added to the database and a list with the online users is generated by the onlineusers.php file. When you click on somebody the messages sent by that person to you and the messages sent by you to that person are shown by the show-messages.php file. When you write a message and press the send button then your message will be sent to the selected user by saving it on the messages table.

Here is the rest of the code:
chat.php
<html>
<head>
<style>
#chat {
width:500px;
margin:0 auto;
}
#login {
width:230px;
height:50px;
margin:100px;
border:1px solid black;
text-indent:10px;
}
.onlineuser {
padding:0 10px;
background:#CCC;
margin-left:2px;
}
.yes {
background:#F90;
}
.message {
float:left;
border:1px solid black;
width:498px;
}
.messdate {
float:right;
}
.selected {
background:red;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>

<body>
<div id="chat"><div id="messages"></div>
<?php mysql_connect('host', 'username', 'password') or die (mysql_error());
mysql_select_db('database') or die (mysql_error());
if(mysql_num_rows(mysql_query("SELECT username FROM chatusers WHERE ip = '" . $_SERVER['REMOTE_ADDR'] . "'")) == 0){ ?>
<div id="login">
Select username: <br />
<input type="text" id="usernameinput"/>
<input type="button" value="Login" id="loginbutton"/>
</div>
<?php }
else {
mysql_query("UPDATE chatusers SET lastactive = " . time() . " WHERE ip = '" . $_SERVER['REMOTE_ADDR'] . "'");
?>
<div id="onlineusers">
</div>
<div id="send">
<textarea id="message" cols="50" rows="5"></textarea><br/><input type="button" value="Send" id="sendbutton" disabled="disabled"/>
</div>
<?php } ?>

<script>
$('#loginbutton').click(function (){
if($(this).attr("disabled") != "disabled"){
var error = $.ajax({
url: "login.php",
data: "username=" + $('#usernameinput').val(),
async:false
}).responseText;
if(error != ''){
alert(error);
}
else {
location.reload();
}
}
});

var from = '';
showusers();
function showusers(){
$('#onlineusers').html($.ajax({
url: 'onlineusers.php?x=' + Math.random() + '&selected=' + from,
async:false
}).responseText);
$('#messages').html($.ajax({
url: 'show-messages.php',
data: '?x=' + Math.random() + '&from=' + from,
async:false
}).responseText);
setTimeout('showusers()',15000);
}

$('.onlineuser').click(function (){
from = $(this).html();
$('#messages').html($.ajax({
url: 'show-messages.php',
data: '?x=' + Math.random() + '&from=' + $(this).html(),
async:false
}).responseText);
$('#sendbutton').removeAttr("disabled");
showusers();
});

$('#sendbutton').click(function (){
if($(this).attr("disabled") != "disabled"){
var message = $('#message').val();
$.ajax({
url: 'send.php?to=' + from + '&mes=' + message
});
$('#message').val('');
showusers();
}
});
</script>
</body>
</html>
onlineusers.php
<?php
mysql_connect('host', 'username', 'password') or die (mysql_error());
mysql_select_db('database') or die (mysql_error());
mysql_query("UPDATE chatusers SET lastactive = " . time() . " WHERE ip = '" . $_SERVER['REMOTE_ADDR'] . "'");
$users = mysql_query("SELECT username FROM chatusers WHERE ip != '" . $_SERVER['REMOTE_ADDR'] . "'");
mysql_query("DELETE FROM chatusers WHERE lastactive < " . (time() - 600)) or die(mysql_error());
echo 'Online users: ';
$username = mysql_fetch_array(mysql_query("SELECT username FROM chatusers WHERE ip = '" . $_SERVER['REMOTE_ADDR'] . "'"));
$username = $username['username'];
while($row = mysql_fetch_array($users)){
$class = '';
$class2 = '';
if(mysql_num_rows(mysql_query("SELECT * FROM messages WHERE sendto = '" . $username . "' and messagefrom = '" . $row['username'] . "'")) > 0) {
$class = 'yes';
}
if($_GET['selected'] == $row['username']){
$class2 = 'selected';
}
echo '<span class="onlineuser ' . $class . ' ' . $class2 . '">' . $row['username'] . '</span>';
}
?>
show-messages.php
<?php
mysql_connect('host', 'username', 'password') or die (mysql_error());
mysql_select_db('database') or die (mysql_error());
$username = mysql_fetch_array(mysql_query("SELECT username FROM chatusers WHERE ip = '" . $_SERVER['REMOTE_ADDR'] . "'"));
$username = $username['username'];
mysql_query("DELETE FROM messages WHERE date < " . (time() - 1800));
$result = mysql_query("(SELECT * FROM messages WHERE messagefrom = '" . $_GET['from'] . "' and sendto = '" . $username . "' ORDER BY date ASC LIMIT 0, 10) UNION (SELECT * FROM messages WHERE messagefrom = '" . $username . "' and sendto = '" . $_GET['from'] . "' ORDER BY date ASC LIMIT 0, 10)") or die(mysql_error());
while($row = mysql_fetch_array($result)){
if($row['messagefrom'] == $username){
$by = 'You';
}
else{
$by = $_GET['from'];
}
echo '<div class="message"><b>' . $by . ':</b> ' . $row['message'] . '<span class="messdate">' . date('g:i A M, d Y',$row['date']) . '</span></div>';
}
?>
login.php
<?php
mysql_connect('host', 'username', 'password') or die (mysql_error());
mysql_select_db('database') or die (mysql_error());
if(mysql_num_rows(mysql_query("SELECT * FROM chatusers WHERE username = '" . $_GET['username'] . "'")) == 0){
mysql_query("INSERT INTO chatusers VALUES('" . $_GET['username'] . "', '" . $_SERVER['REMOTE_ADDR'] . "', " . time() . ")") or die(mysql_error());
}
else{
echo 'Username is taken';
}
?>
send.php
<?php
mysql_connect('host', 'username', 'password') or die (mysql_error());
mysql_select_db('database') or die (mysql_error());
$username = mysql_fetch_array(mysql_query("SELECT username FROM chatusers WHERE ip = '" . $_SERVER['REMOTE_ADDR'] . "'"));
$username = $username['username'];
mysql_query("INSERT INTO messages VALUES('" . $username . "','" . $_GET['to'] . "', '" . $_GET['mes'] . "', " . time() . ")") or die(mysql_error());
?>
If something is not working please let me know!

17 comments:

MobileStimulus.Com said...

I tried it. Cant seem to post...

Csabi said...

Today I will be online for a wile to test the script, but I need somebody to chat with

I think I`we solved the problem

Goran said...

Ola

I am also new to php,
and your previous script is a blast!!!
I am trying to make a private chat,
but all users would be able to talk just to one user,
me, and NOT be able to see others.
Scenario:
I am dispatcher,
and users can only talk to me,
and not to one another,
neither can they see each other.
Is this possible?
Thank you and keep on the GREAT work!

Goran Mitić said...

Hello,
This is great work even as beta!!!

I am interested, if I could show just one or two users,
like moderator users for instance,
and other users can only talk to moderators.
Users should not be able to see each other,
but moderators could see all users.

What I have in mind is like 'help desk' or
like dispatchers, where user can talk just
to one person (moderator).

Thank you and keep the good work!
Kind regards, Goran

Csabi said...

Yes, it can be easily modified, I will post the new code after I modify it and repair some errors ;)

Anonymous said...

cant you something to detect that user has left or entered :)

Csabi said...

an user is logged out after 10 minutes of inactivity, and the script refreshes the online users list each 15 seconds

Anonymous said...

"When you click on somebody the messages sent by that person to you and the messages sent by you to that person are shown by the show-messages.php file" ???? How do you do that. It seems to me that the code for this is half done. Please help :-)

Csabi said...

The secret is in the mysql query
First it selects each message what are sent by you to the selected person,
Secondly it selects each message sent by the selected person to you
Thirdly it combines the results of the two queries

web design bangladesh said...

Great job! Thanks for sharing your concept. I think personally everybody should read the post.

Mak said...

Nice Php Script Keep Posting Some Other Stuff Also

Anonymous said...

Great post!
Can you please tell me if this can be fit to a web site that a user is logged in and private chat with others users logged in?
forgive my bad english

Csabi said...

Yes, you should first remove the "Select username" input and in place just check to see if the user is logged in(on your website) or not. If it`s logged in than in the login.php file in the place of the inputted username use that username with your user is logged in (from session or cookie)

VRONTZOS said...

Greetings!!
i have a site with loged in members using $_SESSSION['username'] and i want members online to have private chat could you please me an e-mail at vrontzos.pan@gmail.com with the code for that?

das said...

In regards to the "dispatcher" posts, all you need to do when you login is have the SEND feature automatically sent to YOU (the dispatcher) and show only messages between YOU and the chatter.

3G Mobiles said...

Tried This But Not Getting To Configure Properly :(

Alex Brunt said...

tried on but doesnt work great progress everything looks right but it wont let me select my username i type it in then click login it doesnt even budge but keep up great work but please help me if i get it fixed and earn money from my website i will pay you $100

Post a Comment

 
Powered by Blogger