PHP/MySQL/Javascript Complete Chat Application
Posted: Thu Aug 11, 2005 4:41 pm
Here's a complete chat application that works with IE, Mozilla, Opera, & Netscape (that's all I've tested) with the following features.
Next we need a login system. I didn't need a login system, because I already had one. So I made a quick one. This should be improved for security.
login.php -- This page lets a user login, or register
Next we need to validate the login.
Validate.php
If all goes well, the main page of the chat should come up. This houses two hidden Iframes.
chat.php -- shows the chat area, userlist, message box, etc
First IFrame hidden in the chat.php page is post.php. This page processes user input and inserts it to the database, and appends to user side.
post.php
The next page is the second hidden IFrame on chat.php. This is by far the most important page of the script, as it grabs new messages (currently set to poll the server once per second) and appends them to the chat for all to see.
thread.php
The following page is the userlist, to show whos in the chat. This page refreshes via javascript every thirty seconds.
userlist.php
And finally, no page would be complete without administration features.
cadmin_frame.php (shows if you are logged in as the super admin)
The following are just two simple pages that users are redirected to when they are kicked or banned from the chat.
chatkick.html
chatban.html
And with that, we are done with this simple chat script. You can give it a try using a demo found at http://www.showmypro.com/chat/chat.php
Register for a username real quick. (takes 3 seconds, and you don't have to check your email)
To test the admin functions, login as test/test (not recommended for simply observing the chat, register a name first).
For conveniance I have zipped all the files up and it can be downloaded at http://www.showmypro.com/chat/chatzip.zip (only 10 kb!)
Edit: Zip file is now 35 kb, as I included the smileys.
- Messages are deleted from the database every 5 seconds, so you don't waste space
New messages are only grabbed when there ARE new messages, so bandwidth is cut to a minimum
Login and login validation.
Registering with a simple form
Note: login features can be easily removed if you already have a login system.
Underline, Italic, Bold, font face, color, and size choices.
22 Emoticons
Link to hyperlink conversion
Shows who has entered the chat room
Super admin features: kick, ban, unban, give mod, take mod
Mod features: kick, ban, unban, give mod, take mod (cannot do anything to super admin)
Real-time chat
No annoying refreshes or flickering chat area
Shows a userlist of whos in the chat
Ermm.. more I just forget
Code: Select all
CREATE TABLE `chat` (
`id` INT( 10 ) NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 25 ) NOT NULL ,
`message` TEXT NOT NULL ,
`timeposted` INT( 25 ) NOT NULL ,
PRIMARY KEY ( `id` )
);
CREATE TABLE `chatuserlist` (
`id` INT( 10 ) NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 25 ) NOT NULL ,
`timeentered` INT( 25 ) NOT NULL ,
`timelastpost` INT( 25 ) NOT NULL ,
`status` CHAR( 1 ) NOT NULL ,
PRIMARY KEY ( `id` )
);
CREATE TABLE `users` (
`id` INT NOT NULL AUTO_INCREMENT ,
`username` VARCHAR( 25 ) NOT NULL ,
`password` CHAR( 32 ) NOT NULL ,
`type` CHAR( 3 ) NOT NULL ,
PRIMARY KEY ( `id` )
);login.php -- This page lets a user login, or register
Code: Select all
<? $db = mysql_connect("localhost","username","password");
mysql_select_db("database_name",$db);
if($_POST['action'] == "register")
{
if(!$_POST['username'] || !$_POST['password'] || !$_POST['password2'])
{
die("You did not complete the form.");
}
if($_POST['password'] != $_POST['password2'])
{
die("Your passwords do not match.");
}
$username = mysql_real_escape_string($_POST['username']);
$password = md5($_POST['password']);
mysql_query("INSERT INTO users (username,password) VALUES('$username','$password')");
echo "You have been registered. Login below.";
} ?>
<HTML>
<HEAD>
<TITLE>Login or Register</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<h4>Login</h4>
<form action="validate.php" method="post">
<input type="hidden" name="action" value="validatelogin">
Username: <input type="text" name="username" size="20"><BR>
Password: <input type="password" name="password" size="20"><BR>
<input type="Submit" value="Login">
</form>
<h4>Not a member?</h4>
<form action="<? echo $_SERVER['php_self']; ?>" method="post">
<input type="hidden" name="action" value="register">
Choose a username (a-z, 0-9, _, 25 chars max)<BR>
<input type="text" name="username" size="20"><BR>
Choose a password (a-z, 0-9, _, 25 chars max)<BR>
<input type="password" name="password" size="20"><BR>
Confirm<BR>
<input type="password" name="password2" size="20"><BR>
<input type="submit" value="Register">
</form>
</BODY>
</HTML>Validate.php
Code: Select all
<? $db = mysql_connect("localhost","username","password");
mysql_select_db("database_name",$db);
if($_POST['action'] == "validatelogin")
{
if(!$_POST['username'] || !$_POST['password'])
{
die("You didn't supply a username or password. Please use the back button on your browser.");
}
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$result = mysql_query("SELECT id FROM users WHERE username = '$username' AND password = '$password'");
if(mysql_num_rows($result) < 1)
{
die("Login error. Either you supplied an incorrect username or password or you have not yet <a href=\"login.php\">registered</a>.");
} ELSE
{
setcookie("username",$username,time()+86400*30);
header("Location: chat.php");
}
} ELSE
{
die("You have reached this page in error.");
}
?>chat.php -- shows the chat area, userlist, message box, etc
Code: Select all
<? $db = mysql_connect("localhost","username","password");
mysql_select_db("database_name",$db);
// Make sure user is logged in,
if(!isset($_COOKIE['username']))
{
header("Location: login.php");
}
// See if the person is banned from the chat
$barray = mysql_fetch_assoc(mysql_query("SELECT type FROM users WHERE username = '$theperson'"));
if($barray['type'] == "ban")
{
die("You are banned from chat. Please contact an administrator.");
}
/* Check to see if the person is currently in the userlist table. If not, insert them. If the user is found, it will update
their time last active, so they aren't deleted from the table. */
$ulcheck = mysql_query("SELECT id FROM chatuserlist WHERE name = '".$_COOKIE['username']."'");
if(mysql_num_rows($ulcheck) < 1)
{
mysql_query("INSERT INTO chatuserlist (name, timeentered, timelastpost) VALUES('".$_COOKIE['username']."', '".time()."', '".time()."')");
} ELSE
{
mysql_query("DELETE FROM chatuserlist WHERE name = '".$_COOKIE['username']."'");
mysql_query("INSERT INTO chatuserlist (name, timeentered, timelastpost) VALUES('".$_COOKIE['username']."', '".time()."', '".time()."')");
}
?>
<!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" lang="en-US" xml:lang="en-US">
<head>
<title>PHP/MySQL/Javascript - DOM - Chat</title>
<script language="javascript">
<!--
function insertSmilie(text) {
text = ' ' + text + ' ';
if (document.frmPost.txtPost.createTextRange && document.frmPost.txtPost.caretPos) {
var caretPos = document.frmPost.txtPost.caretPos;
caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
document.frmPost.txtPost.focus();
} else {
document.frmPost.txtPost.value += text;
document.frmPost.txtPost.focus();
}
}
function insertMessages(content){
var newDiv = document.createElement("DIV");
newDiv.innerHTML = content;
document.getElementById("chattext").appendChild(newDiv);
newDiv.scrollIntoView(false);
}
//-->
</script>
</head>
<body bgcolor="#FFFFFF" onMouseOver="window.status='Chat'; return true">
<table width="740" style="border: solid 1px #000000;" cellspacing="0" cellpadding="0" align="center" bgcolor="#FFFFFF" align="center">
<tr>
<td height="300" valign="top">
<div class="main" style="height: 285px; width: 560px; overflow:auto; padding: 5px;" id="chattext"></div>
</td>
<td height="300" valign="top" style="border-left: solid 1px #000000;">
<iframe src="userlist.php" frameborder="0" height="100%" width="180"></iframe>
</td>
</tr>
<tr>
<td colspan="2" style="border-top: solid 1px #000000; padding: 3px" class="main" bgcolor="#CFED96">
<form action="post.php" method="post" target="post" enctype="application/x-www-form-urlencoded" name="frmPost" id="frmPost">
<B>B</B> <select name="bold"><option value="off" selected>Off</option><option value="on">On</option></select> <B><I>I</I></B> <select name="italics"><option value="off" selected>Off</option><option value="on">On</option></select> <B><U>U</U></B> <select name="underline"><option value="off" selected">Off</option><option value="on">On</option></select> <B>Face:</B>
<select name="face">
<option value="Verdana" selected>Verdana</option>
<option value="Arial">Arial</option>
<option value="Arial Black">Arial Black</option>
<option value="Comic Sans MS">Comic Sans MS</option>
<option value="Courier">Courier</option>
<option value="Courier New">Courier New</option>
<option value="Franklin Gothic Medium">Franklin Gothic Medium</option>
<option value="Gautami">Gautami</option>
<option value="Georgia">Georgia</option>
<option value="Impact">Impact</option>
<option value="Latha">Latha</option>
<option value="Lucida Console">Lucida Console</option>
<option value="Lucida Handwriting">Lucida Handwriting</option>
<option value="Lucida Sans Unicode">Lucida Sans Unicode</option>
<option value="Mangal">Mangal</option>
<option value="Microsoft Sans Serif">Microsoft Sans Serif</option>
<option value="Modern">Modern</option>
<option value="MV Boli">MV Boli</option>
<option value="Palatino Linotype">Palatino Linotype</option>
<option value="Papyrus">Papyrus</option>
<option value="Raavi">Raavi</option>
<option value="Roman">Roman</option>
<option value="Script">Script</option>
<option value="Shruti">Shruti</option>
<option value="Sylfaen">Sylfaen</option>
<option value="Tahoma">Tahoma</option>
<option value="Times New Roman">Times New Roman</option>
<option value="Trebuchet MS">Trebuchet MS</option>
<option value="Tunga">Tunga</option>
<option value="Verdana">Verdana</option>
</select> <B>Size:</B>
<select name="size">
<option value="2" selected>2</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select> <B>Color:</B>
<select name="color">
<option value="black" selected>Black</option>
<option value="blue">Blue</option>
<option value="#9999FF">Light Blue</option>
<option value="brown">Brown</option>
<option value="#CCCCCC">Gray</option>
<option value="green">Green</option>
<option value="66FF33">Lime Green</option>
<option value="orange">Orange</option>
<option value="pink">Light Pink</option>
<option value="#FF33CC">Pink</option>
<option value="purple">Purple</option>
<option value="red">Red</option>
<option value="yellow">Yellow</option>
</select><BR><BR>
<B>Message:</B> <input type="text" size="40" name="message" style="border: solid 1px #000000" id="txtPost">
<input type="submit" value="Send">
</form>
<a href="#" OnClick="insertSmilie(':arrow:'); return false;"><img src="smilies/arrow.gif" alt="Arrow" border="0"></a> <a href="#" OnClick="insertSmilie(';-D'); return false;"><img src="smilies/badgrin.gif" alt="Bad Grin" border="0"></a> <a href="#" OnClick="insertSmilie(':-D'); return false;"><img src="smilies/biggrin.gif" alt="Big Grin" border="0"></a> <a href="#" OnClick="insertSmilie(':-S'); return false;"><img src="smilies/confused.gif" alt="Confused" border="0"></a> <a href="#" OnClick="insertSmilie('B-)'); return false;"><img src="smilies/cool.gif" alt="Cool" border="0"></a> <a href="#" OnClick="insertSmilie(':(('); return false;"><img src="smilies/cry.gif" alt="Cry" border="0"></a> <a href="#" OnClick="insertSmilie(':-/'); return false;"><img src="smilies/doubt.gif" alt="Doubt" border="0"></a> <a href="#" OnClick="insertSmilie('V:)'); return false;"><img src="smilies/evil.gif" alt="Evil" border="0"></a>
<a href="#" OnClick="insertSmilie(':-!'); return false;"><img src="smilies/exclaim.gif" alt="Exclaim" border="0"></a> <a href="#" OnClick="insertSmilie('o-)'); return false;"><img src="smilies/idea.gif" alt="Idea" border="0"></a> <a href="#" OnClick="insertSmilie(':))'); return false;"><img src="smilies/lol.gif" alt="Lol" border="0"></a> <a href="#" OnClick="insertSmilie('x-('); return false;"><img src="smilies/mad.gif" alt="Mad" border="0"></a> <a href="#" OnClick="insertSmilie(':-|'); return false;"><img src="smilies/neutral.gif" alt="Neutral" border="0"></a> <a href="#" OnClick="insertSmilie(':-?'); return false;"><img src="smilies/question.gif" alt="Question" border="0"></a> <a href="#" OnClick="insertSmilie(':-P'); return false;"><img src="smilies/razz.gif" alt="Razz" border="0"></a> <a href="#" OnClick="insertSmilie(':-$'); return false;"><img src="smilies/redface.gif" alt="Redface" border="0"></a>
<a href="#" OnClick="insertSmilie('8-|'); return false;"><img src="smilies/rolleyes.gif" alt="Roll Eyes" border="0"></a> <a href="#" OnClick="insertSmilie(':-('); return false;"><img src="smilies/sad.gif" alt="Sad" border="0"></a> <a href="#" OnClick="insertSmilie(':-o'); return false;"><img src="smilies/shock.gif" alt="Shock" border="0"></a> <a href="#" OnClick="insertSmilie(':-)'); return false;"><img src="smilies/smile.gif" alt="Smile" border="0"></a> <a href="#" OnClick="insertSmilie(':.o'); return false;"><img src="smilies/surprised.gif" alt="Surprised" border="0"></a> <a href="#" OnClick="insertSmilie(';-)'); return false;"><img src="smilies/wink.gif" alt="Wink" border="0"></a>
</td>
</tr>
<tr>
<td colspan="2">
<iframe id="post" name="post" src="post.php" style="width: 0px; height: 0px; border: 0px;"></iframe>
<iframe id="thread" name="thread" src="thread.php" style="width: 0px; height: 0px; border: 0px;"></iframe>
</td>
</tr>
</table>
<? // See if the user logged in is a mod, if so, show admin functions
$modarray = mysql_fetch_assoc(mysql_query("SELECT type FROM users WHERE username = '".$_COOKIE['username']."'"));
if($modarray['type'] == "mod")
{ ?>
<div align="center"><iframe src="cadmin_frame.php" frameborder="0" width="740" height="300"></iframe><?
} ?>
</body>
</html>post.php
Code: Select all
<? $db = mysql_connect("localhost","username","password");
mysql_select_db("database_name",$db);
// Make sure user is logged in
if(!isset($_COOKIE['username'])){ die(); }
if($_COOKIE['username'] == ""){ die(); }
if(sizeof($_POST['message']))
{
// The javascript below clears the message box on the chat.php page and gives it focus
?>
<script type="text/javascript"><!--
parent.document.getElementById("txtPost").value = "";
parent.document.getElementById("txtPost").focus();
//-->
</script>
<?
// See if the user is in the chatuserlist table, perhaps they have idled and are no longer in there, but are posting now, so reinsert them
$ulquery = mysql_query("SELECT id FROM chatuserlist WHERE name = '".$_COOKIE['username']."'");
if(mysql_num_rows($ulquery) < 1)
{
mysql_query("INSERT INTO chatuserlist (name, timeentered, timelastpost) VALUES('".$_COOKIE['username']."', '".time()."', '".time()."')");
}
// Delete messages older than 5 seconds to cut back on database space
$expiretime = time() - 5;
mysql_query("DELETE FROM chat WHERE timeposted <= '$expiretime'");
// Update the users timelastactive so they remain 'active' in the userlist script
mysql_query("UPDATE chatuserlist SET timelastpost = '".time()."' WHERE name = '".$_COOKIE['username']."'");
// Here we are configuring the users font preferences
$name = $_COOKIE['username'];
$bold = $_POST['bold'];
$italic = $_POST['italics'];
$underline = $_POST['underline'];
$face = $_POST['face'];
$size = $_POST['size'];
$color = $_POST['color'];
$message = $_POST['message'];
$timeposted = time();
if($bold == "on"){ $b12 = "<B>"; $b22 = "</B>"; } ELSE { $b12 = ""; $b22 = ""; }
if($italic == "on"){ $i12 = "<I>"; $i22 = "</I>"; } ELSE { $i12 = ""; $i22 = ""; }
if($underline == "on"){ $u12 = "<U>"; $u22 = "</U>"; } ELSE { $u12 = ""; $u22 = ""; }
// Make the entry safe for the database
$message2 = htmlentities($message, ENT_QUOTES);
// Convert links to hyperlinks
function make_clickable($text)
{
$ret = ' ' . $text;
$ret = preg_replace("#(^|[\n ])([\w]+?://[^ \"\n\r\t<]*)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $ret);
$ret = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r<]*)#is", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $ret);
$ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret);
$ret = substr($ret, 1);
return($ret);
}
$message3 = make_clickable($message2);
// Store the converted message in a string
$message4 = "<font face=\"$face\" size=\"$size\" color=\"$color\">$b12$i12$u12$message3$u22$i22$b22</font>";
// This next line overcomes a bug in the smiley conversion
$message5 = str_replace(":))", " )", $message4);
// Convert all text for smilies into the appropriate smiley image
$smilies = array(":arrow:",";-D",";-d",";-D",";-d",":-D",":-d",":D",":d",":-S",":-s",":S",":s","B-)","b-)",":((",":-/",":-/","v:)","V:)",":-!",":!","o-)","O-)",":))","X-(","x-(","X(","x(",":-|",":|",":-?",":?",":-P",":-p",":P",":p",":-$",":$","8-|","8|",":-(",":(",":-O",":-o",":O",":o",":-)",":)",":.O",":.o",";-)",";)");
$smiliesimg = array("<img src=smilies/arrow.gif>","<img src=smilies/badgrin.gif>","<img src=smilies/badgrin.gif>","<img src=smilies/badgrin.gif>","<img src=smilies/badgrin.gif>","<img src=smilies/biggrin.gif>","<img src=smilies/biggrin.gif>","<img src=smilies/biggrin.gif>","<img src=smilies/biggrin.gif>","<img src=smilies/confused.gif>","<img src=smilies/confused.gif>","<img src=smilies/confused.gif>","<img src=smilies/confused.gif>","<img src=smilies/cool.gif>","<img src=smilies/cool.gif>","<img src=smilies/cry.gif>","<img src=smilies/doubt.gif>","<img src=smilies/doubt.gif>","<img src=smilies/evil.gif>","<img src=smilies/evil.gif>","<img src=smilies/exclaim.gif>","<img src=smilies/exclaim.gif>","<img src=smilies/idea.gif>","<img src=smilies/idea.gif>","<img src=smilies/lol.gif>","<img src=smilies/mad.gif>","<img src=smilies/mad.gif>","<img src=smilies/mad.gif>","<img src=smilies/mad.gif>","<img src=smilies/neutral.gif>","<img src=smilies/neutral.gif>","<img src=smilies/question.gif>","<img src=smilies/question.gif>","<img src=smilies/razz.gif>","<img src=smilies/razz.gif>","<img src=smilies/razz.gif>","<img src=smilies/razz.gif>","<img src=smilies/redface.gif>","<img src=smilies/redface.gif>","<img src=smilies/rolleyes.gif>","<img src=smilies/rolleyes.gif>","<img src=smilies/sad.gif>","<img src=smilies/sad.gif>","<img src=smilies/shock.gif>","<img src=smilies/shock.gif>","<img src=smilies/shock.gif>","<img src=smilies/shock.gif>","<img src=smilies/smile.gif>","<img src=smilies/smile.gif>","<img src=smilies/surprised.gif>","<img src=smilies/surprised.gif>","<img src=smilies/wink.gif>","<img src=smilies/wink.gif>");
$message6 = stripslashes(str_replace($smilies, $smiliesimg, $message5));
// Insert the message into the database
mysql_query("INSERT INTO chat (name, message, timeposted) VALUES('$name','<B>".$_COOKIE['username']."</B>: $message6', '$timeposted')");
// Below is a javascript to append the message to the users side so the message 'appears' instantaneously
?>
<div id="chattext2"><B><? echo $_COOKIE['username']; ?></B>: <? echo $message6; ?></div>
<script type="text/javascript">
<!--
if(parent.insertMessages && document.getElementById("chattext2"))
parent.insertMessages(document.getElementById("chattext2").innerHTML);
//-->
</script>
<?
// For some reason, exit(); is needed to keep the message from appending twice?
exit();
} ?>
<!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" lang="en-US" xml:lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
</body>
</html>thread.php
Code: Select all
<? $db = mysql_connect("localhost","username","password");
mysql_select_db("database_name",$db);
// We will need to start a session
session_start();
$currtime = time();
// If the user has been banned, we will send them an alert which redirects them to the chat ban page
// This is permanent, so it will need to be stored in the users table
$barray = mysql_fetch_assoc(mysql_query("SELECT type FROM users WHERE username = '".$_COOKIE['username']."'"));
if($barray['type'] == "ban")
{ ?>
<script type="text/javascript">
<!--
alert("You have been banned from the chat.");
parent.location.href = 'chatban.html';
//-->
</script><?
die();
}
// If a user has been kicked, we will send them an alert and then redirect them to the chat kick page
// This is not permanent, so storing it in the chatuserlist table will be fine
$sarray = mysql_fetch_assoc(mysql_query("SELECT status FROM chatuserlist WHERE name = '".$_COOKIE['username']."'"));
if($sarray['status'] == "1")
{ ?>
<script type="text/javascript">
<!--
alert("You have been kicked from the chat.");
parent.location.href = 'http://www.showmypro.com/chatkick.html';
//-->
</script><?
die();
}
// Grab new messages since this page last refreshed, and the username isn't the $_COOKIE['username'] because their message
// was already appended to their side
// $res
$res = mysql_query("SELECT name, message FROM chat WHERE name != '".$_COOKIE['username']."' AND timeposted >= '".$_SESSION['prevtime']."' AND timeposted < '$currtime' ORDER BY timeposted");
?>
<!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" lang="en-US" xml:lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?
// IF there are new messages, select them for appending to the chat area
if(mysql_num_rows($res))
{
echo '<div id="contents">';
while($row = mysql_fetch_assoc($res))
{
echo "<div>".$row['message']."</div>";
}
echo '</div>';
}
// These following lines will tell us when other users have entered the room
$userquery = mysql_query("SELECT name FROM chatuserlist WHERE timeentered >= '".$_SESSION['prevtime']."' AND timeentered < '$currtime'");
if(mysql_num_rows($userquery))
{
echo '<div id="contents">';
while($userarray = mysql_fetch_assoc($userquery))
{
echo '<div><font color="red" face="tahoma" size="2">' . $userarray['name'] . ' has entered the room.</font>';
}
echo '</div>';
}
// Delete non-active members from the userlist
$userlistet = time() - 300;
mysql_query("DELETE FROM chatuserlist WHERE timelastpost <= '$userlistet' AND timelastpost != '0'");
// Set session variable for use with new message checking
$_SESSION['prevtime'] = $currtime;
// The following javascript appends all new messages to the chat contents area, and refreshes the page seamlessly every second
?>
<script type="text/javascript">
<!--
if(parent.insertMessages && document.getElementById("contents"))
parent.insertMessages(document.getElementById("contents").innerHTML);
//-->
</script>
<script type="text/javascript">
<!--
setTimeout("getMessages()",1000);
function getMessages(){ document.location.reload(); }
//-->
</script>
</body>
</html>userlist.php
Code: Select all
<html>
<head>
<title>Chat Userlist</title>
</head>
<body topmargin="5" leftmargin="5" bgcolor="#FFFFFF">
<U>Users</u><BR>
<? $db = mysql_connect("localhost","username","password");
mysql_select_db("database_name",$db);
// Since we're using PHP, determining who's REALLY in the chat is quite hard
// So we will have to see whos been active within the last five minutes
// The following line deletes users no longer active in the past five minutes
$userlistet = time() - 300;
mysql_query("DELETE FROM chatuserlist WHERE timelastpost <= '$userlistet' AND timelastpost != '0'");
// Grab users in the userlist
$query = mysql_query("SELECT name FROM chatuserlist ORDER BY name ASC");
if(mysql_num_rows($query) < 1)
{
echo "No Users";
} ELSE
{
while($array = mysql_fetch_assoc($query))
{
echo "<B>".$array['name']."</B><BR>";
}
}
// The following javascript seamlessly refreshes the user list every 30 seconds
?>
<script type="text/javascript">
<!--
setTimeout("getUserlist()",30000);
function getUserlist(){ document.location.reload(); }
//-->
</script>
</body>
</html>cadmin_frame.php (shows if you are logged in as the super admin)
Code: Select all
<html>
<head>
<title>Chat Admin</title>
</head>
<body bgcolor="#FFFFFF">
<? $db = mysql_connect("localhost","username","password");
mysql_select_db("database_name",$db);
if($_POST['action'] == "kickuser")
{
if($_POST['usertokick'] == "test")
{
echo "<font color=red><B>You cannot kick this user.</B></font>";
} ELSE
{
mysql_query("UPDATE chatuserlist SET status = '1' WHERE name = '".$_POST['usertokick']."'");
echo "<font color=red><B>User has been kicked.</B></font>";
}
}
if($_POST['action'] == "banuser")
{
if($_POST['usertokick'] == "test")
{
echo "<font color=red><B>You cannot ban this user.</B></font>";
} ELSE
{
mysql_query("UPDATE users SET type = 'ban' WHERE username = '".$_POST['usertoban']."'");
echo "<font color=red><B>User has been banned.</B></font>";
}
}
if($_POST['action'] == "unbanuser")
{
mysql_query("UPDATE users SET type = '' WHERE username = '".$_POST['usertounban']."'");
echo "<font color=red><B>User has been unbanned.</B></font>";
}
if($_POST['action'] == "givemod")
{
mysql_query("UPDATE users SET type = 'mod' WHERE username = '".$_POST['modtogive']."'");
echo "<font color=red><B>User has been given mod status.</B></font>";
}
if($_POST['action'] == "takemod")
{
if($_POST['modtotake'] == "test")
{
echo "<font color=red><B>You cannot take mod from this user.</B></font>";
} ELSE
{
mysql_query("UPDATE users SET type = '' WHERE username = '".$_POST['modtotake']."'");
echo "<font color=red><B>Mod status has been taken away from user.</B></font>";
}
}
?>
<form action="<? echo $_SERVER['php_self']; ?>" method="post">
<input type="hidden" name="action" value="kickuser">
<B>Kick User:</B> <input type="text" name="usertokick" size="20">
<input type="submit" value="Kick">
</form>
<form action="<? echo $_SERVER['php_self']; ?>" method="post">
<input type="hidden" name="action" value="banuser">
<B>Ban User:</B> <input type="text" name="usertoban" size="20">
<input type="submit" value="Ban">
</form>
<form action="<? echo $_SERVER['php_self']; ?>" method="post">
<input type="hidden" name="action" value="unbanuser">
<B>Unban User:</B> <select name="usertounban">
<option selected>Select</option><?
$buquery = mysql_query("SELECT username FROM users WHERE type = 'ban' ORDER BY username ASC");
while($buarray = mysql_fetch_assoc($buquery))
{ ?>
<option value="<? echo $buarray['username']; ?>"><? echo $buarray['username']; ?></option><?
} ?>
<input type="submit" value="Unban">
</form>
<form action="<? echo $_SERVER['php_self']; ?>" method="post">
<input type="hidden" name="action" value="givemod">
<B>Give Mod:</B> <input type="text" name="modtogive" size="20">
<input type="submit" value="Give">
</form>
<form action="<? echo $_SERVER['php_self']; ?>" method="post">
<input type="hidden" name="action" value="takemod">
<B>Take Mod:</B> <input type="text" name="modtotake" size="20">
<input type="submit" value="Take">
</form>
</body>
</html>chatkick.html
Code: Select all
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>
Chat Ban
</title>
</head>
<body bgcolor="#ffffff">
You have been kicked from chat by an administrator.
</body>
</html>Code: Select all
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>
Chat Ban
</title>
</head>
<body bgcolor="#ffffff">
You have been banned from chat by an administrator.
</body>
</html>Register for a username real quick. (takes 3 seconds, and you don't have to check your email)
To test the admin functions, login as test/test (not recommended for simply observing the chat, register a name first).
For conveniance I have zipped all the files up and it can be downloaded at http://www.showmypro.com/chat/chatzip.zip (only 10 kb!)
Edit: Zip file is now 35 kb, as I included the smileys.