Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Private chat room system using PHP, jQuery and MySQL

ajax mysql jquery

  • Please log in to reply
5 replies to this topic

#1 Csabi

Csabi

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 60 posts

Posted 07 January 2011 - 12:56 PM

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: private chat room script
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! Private chat script, here is the original tutorial, here you can find out more about the script.
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#2 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 09 January 2011 - 03:53 PM

Thanks for sharing, but I have unapproved this thread. Please fix your SQL injections, and I will re-approve.
  • 0

#3 Csabi

Csabi

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 60 posts

Posted 10 January 2011 - 04:33 AM

What is wrong with the sql injectons ? :)
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#4 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 10 January 2011 - 08:22 AM

http://forum.codecal...injections.html

You are using user manipulated data directly in your query.
  • 0

#5 Csabi

Csabi

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 60 posts

Posted 10 January 2011 - 11:41 AM

Wow, that was a really useful tutorial, it scared me: a website can be hacked so easily....
But I had not used very secure (or not secure) injections because the users are not sharing any passwords or any data that would worth to hack.... and even if somebody would hack it, he would not be able to send a message from another persons name, because the user is selected based on it`s IP
And even the messages are displayed based on IP

But if it`s really necessary to bring some more security just let me know and I will do what I can :)
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#6 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 10 January 2011 - 12:15 PM

Well, bypassing login security is just one application of SQL injections. ANY SQL can be injected such as DROP FROM or TRUNCATE which will delete your data. There is probably a bunch of other nasty things hackers can do as well that are beyond my imagination. Adding a few extra lines of code is not much to ask for a secure application.
  • 0





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download