Chat Room Login
The chat room script below does three things. Allows users to sign up, allows users to log in, or allows users to delete their chat accounts. A welcoming email will be sent to new users once they register. The script below will actually create needed MySQL tables in the database if none are found, as long as the correct info has been inserted into the config.php file by the chat room webmaster. Note that $countrecords = mysql_result(mysql_query('SELECT COUNT(*) FROM emoticons'), 0); is a great way to check if a table is empty so the script can load the table with gif names only once, based on whether or not the table is or is not empty. Even though script users will be saving the actual gifs in a folder called emoticons, we also need the names in a convenient array which could be stored in a PHP array or a MySQL table. We chose the latter, although they end up in an array anyway. The $gifs array is declared and the emoticons' names are gotten from a MySQL database table called emoticons and stuck, using PHP's array_push function, into the $gifs array. We guess it's just kind of secure knowing that they are stored in a table, even if it was not essential.
On to the code: The functions validatepasswordlogin() (for login), validatepassword() (for registration), and validatedump() (for account deletion) check the user's input to make sure it is legit. The registration input will also be checked in the PHP code—feel free to write PHP validators for the login and account deletion inputs as well. We were mostly concerned with spammers using their automated spam robots to sign up—our PHP validation script will catch them if they have JavaScript disabled so miss those validators. Note that the JavaScript focus() function keeps the cursor on the input box until the input is legit at which point the script does a return true.
The function validatedump() serves two purposes: ensuring the user's info is legit, and using a JavaScript confirm() function to make sure the specific MySQL record deletion is desired. Note that the user name being dumped is pulled from the input box that selects it, which is the account deletion form.
On to the PHP code. As usual, we start with config.php, since without it, the MySQL-based app would not be viable. You cannot relate to a db without knowing the magic words. Use of htaccess on any configuration files will be of great help here. FTP this (exactly as you see it—do NOT edit) to your chat folder after saving it as htaccess:
<Files "config.php">
order deny,allow
deny from all
</Files>
Options -Indexes
The mix() function hashes the password, one character at a time, with md5(), then does a sha512() hash on the result before it gets trimmed down to 65 characters.
The next script is the table creation script. The first table updates the current time, to the second, when ANYONE submits a chat comment. (In relating to time, we use date_default_timezone_set('UTC') to set the time zone to Coordinated Universal Time, which is UTC, and them subtract 14 seconds and add 14400 seconds. The format is strtotime("now")-14+14400 to get 14 seconds ago and this is compared to the UNIX_TIMESTAMP() value of the datetime numbers we store in our db table. You'll see why when you check out the chat room scripts. The 14400 is because our server's time is 4 hours ahead of UTC. Both the SQL function UNIX_TIMESTAMP() and the PHP strtotime() function give the number of seconds since 1970, so they're comparable. We use datetime values, not timestamps, but the timestamp function shown is the right one for conversion—perhaps the only SQL function that will do the needed job.) You can see that chat room users get a lot of data stored about them like id, password, user name, email, date they registered, screen name, IP, whether they are logged in now, if they are in a private chat, screen name of their private chat partner, which of their 5 saved chat comment fields was last saved to, and the last five dates of comments and content of comments.
The input data gets POSTed to the PHP, next, with $U getting the user name, $upassword getting his password, $S getting the screen name of the user, and $email getting the email. There's also $L which gets their answer to our captcha, which consists of a sentence and a question about the sentence which is easy for people but not easy for spam robots. If they miss it, the page reloads.
Next, if the registration form has just been submitted the PHP input validation script gets run to make sure the registration user name and password and other data are OK. The PHP preg_match() function is used, with regular expressions, in the PHP scripts that ensure that proper characters only have been typed. If not, a JavaScript alert message is shown. The series of }else{ conditionals ensures that if there is a problem with login input, the script goes no further. If all is well, an email is sent to them welcoming them to the chat room and the db table is updated to include this new registrant.
Next, if the login form has just been submitted the PHP script checks to make sure the login user name exists and the username/password pair are valid. If so, their record in the MySQL db is updated to show they are logged in and they are taken to the chat room.
Next, if the account deletion form has just been submitted the PHP script checks to make sure the login user name exists and the username/password pair are valid. If so, their record in the MySQL db is deleted and they are taken to the http://css-resources.com website. (Had to take them somewhere!)
All three scripts, the registration, login, and account deletion scripts all use the mix() function to hash any password. After doing so, the result, $c, is compared with the password hash stored in the chatroommembers MySQL db table. Note that their actual password is never stored—why give hackers an easy mark? This means if someone forgets their password and asks for it, you simply cry crocodile tears as you explain you do not know it either so they must re-register.
Next, the HTML login forms are pretty standard stuff. Note that each form tag uses an onsubmit event to run the JavaScript input validators before form submission actually occurs.
Save this file as chat-room-login.php
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
<TITLE>Chat Room Login</TITLE>
<meta name="description" content="Chat Room Login Script">
<meta name="keywords" content="Chat Room Login Script,chatroom,chat room,login,php,javascript, dhtml, DHTML">
<style type="text/css">
BODY {margin-left:0; margin-right:0; margin-top:0;text-align:left}
p, li {font:13px Verdana; color:black;text-align:left}
h1 {font:bold 28px Verdana; color:black;text-align:center}
h2 {font:bold 24px Verdana;text-align:center}
h3 {font:bold 15px Verdana;}
</style>
<script language="javascript">
function validatepassword(){
var ck_password = /^[A-Za-z0-9!@#$%^&*()_]{4,20}$/;
if (document.formpw.upassword.value.search(ck_password)==-1)
{alert("Please only enter letters, numbers and these for the password: !@#$%^&*()_");
document.formpw.upassword.focus();return false}
var ck_username = /^[A-Za-z0-9_]{6,20}$/;
if (document.formpw.username.value.search(ck_username)==-1)
{alert("Please only enter 6 to 20 letters, numbers and underline for the user name.");document.formpw.username.focus();
return false}
var ck_screen_name = /^[A-Za-z0-9_]{6,20}$/;
if (document.formpw.screen_name.value.search(ck_screen_name)==-1)
{alert("Please only enter 6 to 20 letters, numbers and underline for the screen name.");document.formpw.screen_name.focus();
return false}
var ck_email = /^[A-Za-z0-9-_]+(\.[A-Za-z0-9-_]+)*@([A-Za-z0-9-_]+\.)?([A-Za-z0-9-_]+(\.[A-Za-z]{2,6})(\.[A-Za-z]{2})?)$/;
if (document.formpw.email.value.search(ck_email)==-1)
{alert("That email address is not valid. Try again.");document.formpw.email.focus();return false;}
return true;}
function validatepasswordlogin(){
var ck_password = /^[A-Za-z0-9!@#$%^&*()_]{4,20}$/;
if (document.formlogin.upasswordlogin.value.search(ck_password)==-1)
{alert("Please only enter letters, numbers and these for the password: !@#$%^&*()_");
document.formlogin.upasswordlogin.focus();return false}
var ck_username = /^[A-Za-z0-9_]{6,20}$/;
if (document.formlogin.uname.value.search(ck_username)==-1)
{alert("Please only enter 6 to 20 letters, numbers and underline for the user name.");document.formlogin.uname.focus();
return false}
return true;}
function validatedump(){
var ck_password = /^[A-Za-z0-9!@#$%^&*()_]{4,20}$/;
if (document.formdump.dumppassword.value.search(ck_password)==-1)
{alert("Please only enter letters, numbers and these for the password: !@#$%^&*()_");
document.formdump.dumppassword.focus();return false}
var ck_username = /^[A-Za-z0-9_]{6,20}$/;
if (document.formdump.dumpname.value.search(ck_username)==-1)
{alert("Please only enter 6 to 20 letters, numbers and underline for the user name.");document.formdump.dumpname.focus();
return false}
var nme=document.formdump.dumpname.value;
var answer = confirm("Attention, "+nme+", your account will be deleted. OK?");
if (!answer){alert("deletion aborted");return false}
return true;}
</script>
</head>
<body>
<?php
include_once"config.php";
function mix(){
global $upassword, $c;
$p = str_split($upassword);
foreach ($p as $h){$m .= md5($h);}
$c = hash('sha512',$m);
$c = substr($c, 0, 65);}
$sql = "CREATE TABLE IF NOT EXISTS changed (
id int(4) NOT NULL,
date_changed datetime NOT NULL,
counter tinyint(2) NOT NULL default '0',
PRIMARY KEY (id)
)";
$sql = "CREATE TABLE IF NOT EXISTS chatroommembers (
id int(4) NOT NULL auto_increment,
username varchar(20) NOT NULL,
upassword varchar(65) NOT NULL,
email varchar(65) NOT NULL,
ip varchar(65) NOT NULL,
date varchar(25) NOT NULL,
screen_name varchar(20) NOT NULL,
logged_in tinyint(2) NOT NULL default '0',
entry tinyint(2) NOT NULL default '0',
priv_if tinyint(2) NOT NULL default '0',
priv_who varchar(20) NOT NULL,
datetime0 datetime NOT NULL,
chat0 text NOT NULL,
datetime1 datetime NOT NULL,
chat1 text NOT NULL,
datetime2 datetime NOT NULL,
chat2 text NOT NULL,
datetime3 datetime NOT NULL,
chat3 text NOT NULL,
datetime4 datetime NOT NULL,
chat4 text NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=1";
// Execute query
mysql_query($sql);
$sql = "CREATE TABLE IF NOT EXISTS emoticons (
id int(4) NOT NULL auto_increment,
gif varchar(30) NOT NULL default '',
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=1";
// Execute query
mysql_query($sql);
$countrecords = mysql_result(mysql_query('SELECT COUNT(*) FROM emoticons'), 0);
if(!$countrecords){
$emoticons_names = mysql_query("INSERT INTO emoticons (id, gif) VALUES
(1, 'nose-grows.gif'),
(2, 'fangs.gif'),
(3, 'clown.gif'),
(4, 'king.gif'),
(5, 'professor.gif'),
(6, 'loudmouth.gif'),
(7, 'telephone.gif'),
(8, 'joker.gif'),
(9, 'confused-smiley-013.gif'),
(10, 'alien.gif'),
(11, 'wave.gif'),
(12, 'what-the-hell.gif'),
(13, 'tongue2.gif'),
(14, 'tongue.gif'),
(15, 'winker.gif'),
(16, 'ick.gif'),
(17, 'more-mooning.gif'),
(18, 'wiggle.gif'),
(19, 'whoaaaa.gif'),
(20, 'mooning.gif'),
(21, 'clapping.gif'),
(22, 'hammer-to-head.gif'),
(23, 'no.gif'),
(24, 'whipping.gif'),
(25, 'lip-licker.gif'),
(26, 'action-rock-out-dude.gif'),
(27, 'gun-to-head.gif'),
(28, 'dead-drunk.gif'),
(29, 'blah-blah.gif'),
(30, 'frazzled.gif'),
(31, 'say-whattttt.gif'),
(32, 'action-nutty.gif'),
(33, 'glasses.gif'),
(34, 'mischief.gif'),
(35, 'innocent.gif'),
(36, 'whatever.gif'),
(37, 'angel_sm001.gif'),
(38, 'smile-cool.gif'),
(39, 'cool-smiley-004.gif'),
(40, 'scared.gif'),
(41, 'panic.gif'),
(42, 'sleeping.gif'),
(43, 'vomit-smiley-012.gif'),
(44, 'sad-smiley-046.gif'),
(45, 'jump.gif'),
(46, 'love003.gif'),
(47, 'laughing-smiley-001.gif'),
(48, 'grinning-smiley-007.gif'),
(49, 'devil-smiley-002.gif'),
(50, 'confused-smiley-001.gif'),
(51, 'mad-.gif'),
(52, 'smilie_poodle1.gif'),
(53, 'stubborn.gif')") or die(mysql_error());}
if(isset($_POST['register'])){
$U = $_POST['username'];
$S = $_POST['screen_name'];
$L = $_POST['captcha'];if ($L<>"of"){
echo '<script language="javascript">alert("Please answer question."); window.location = "chat-room-login.php"; </script>';
}else{$L="crapola";}
$U = strip_tags($U);
if (!preg_match("/[A-Za-z0-9_]{6,20}$/",$U)) {
echo '<script language="javascript">alert("Please enter 6 to 20 letters, numbers and underline for username."); window.location = "chat-room-login.php"; </script>';
}else{
$S = strip_tags($S);
if (!preg_match("/[A-Za-z0-9_]{6,20}$/",$S)) {
echo '<script language="javascript">alert("Please enter 6 to 20 letters, numbers and underline for screen name."); window.location = "chat-room-login.php"; </script>';
}else{
$upassword = $_POST['upassword'];
if (strlen($upassword)<6 || strlen($upassword)>20) {
echo '<script language="javascript">alert("Please enter 6 to 20 characters for password."); window.location = "chat-room-login.php"; </script>';
}else{
$email = $_POST['email'];
$email = strip_tags($email);
$email = htmlspecialchars($email, ENT_QUOTES);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
echo '<script language="javascript">alert("That email address is not valid."); window.location = "chat-room-login.php"; </script>';
}else{
$memip = $_SERVER['REMOTE_ADDR'];
$date = date("d-m-Y");
$checkformembers = mysql_query("SELECT * FROM chatroommembers WHERE username = '$U'");
if(mysql_num_rows($checkformembers) != 0){echo '<script language="javascript">alert("Username already in use. Please try again.")</script>;';
}else{
$checkforscreenname = mysql_query("SELECT * FROM chatroommembers WHERE screen_name = '$S'");
if(mysql_num_rows($checkforscreenname) != 0){echo '<script language="javascript">alert("Screen name already in use. Please try again.")</script>;';
}else{
mix();
if($L=="crapola"){
$create_member = mysql_query("INSERT INTO chatroommembers (id, username, upassword, email, ip, date, screen_name, logged_in)
VALUES('','$U','$c','$email','$memip','$date','$S','40')") or die(mysql_error());
$to = $email;
$subject = "Welcome to the Chat Room!";
$message = "You've successfully registered as Chat Room member.\n\nYour user name is ".$U.".\n\nYour screen name is ".$S.".\n\nYou may now go to the Chat Room and chat.\n\nDon't give your password to anyone, but do save it somewhere safe.\n\nEnjoy the Chat Room!\n\nRegards,\n\nthe Chat Room management";
$headers = "From: ".$psbhostemailaddress."\r\nReply-To: ".$email;
$mail_sent = mail($to, $subject, $message, $headers);
echo '<BR><BR><script language="javascript">alert("Thank you for registering.");window.location = "cms-chat-room.php?username='.$U.'&st=1";</script>';}}}}}}}}
if(isset($_POST['login'])&&isset($_POST['uname'])&&isset($_POST['upasswordlogin'])){
$U = $_POST['uname'];
$P = $_POST['upasswordlogin'];$upassword=$P;mix();
$check_user_data = mysql_query("SELECT * FROM chatroommembers WHERE username = '$U'") or die(mysql_error());
if(mysql_num_rows($check_user_data) == 0)
{echo '<script language="javascript">alert("This user name does not exist. Please try again.")</script>;';unset($U);unset($P);
}else{
$get_user_data = mysql_fetch_array($check_user_data);
$Z=$get_user_data['upassword'];
if($Z != $c || !isset($_POST['login']))
{echo '<script language="javascript">alert("Username/password pair is invalid. Please try again.")</script>;';unset($U);unset($P);
}else{
$login = mysql_query("UPDATE chatroommembers SET logged_in='40' WHERE username = '$U'") or die(mysql_error());
echo '<script language="javascript">window.location = "cms-chat-room.php?username='.$U.'&st=1";</script>';}}}
if(isset($_POST['dumplogin'])&&isset($_POST['dumpname'])&&isset($_POST['dumppassword'])){
$U = $_POST['dumpname'];
$P = $_POST['dumppassword'];$upassword=$P;mix();
$check_user_data = mysql_query("SELECT * FROM chatroommembers WHERE username = '$U'") or die(mysql_error());
if(mysql_num_rows($check_user_data) == 0)
{echo '<script language="javascript">alert("This user name does not exist. Please try again.")</script>;';unset($U);unset($P);
}else{
$get_user_data = mysql_fetch_array($check_user_data);
$Z=$get_user_data['upassword'];
if($Z != $c || !isset($_POST['dumplogin']))
{echo '<script language="javascript">alert("Username/password pair is invalid. Please try again.")</script>;';unset($U);unset($P);
}else{
$dump = "DELETE FROM chatroommembers WHERE username = '$U'";
$result=mysql_query($dump) or die('Error ,deleting failed');
$rc = mysql_affected_rows();
if ($rc>0){echo '<script language="javascript">alert("The account deleting was successfully accomplished.");window.location ="http://css-resources.com"; </script>';}
else{echo '<script language="javascript">alert("Deleting failed.");window.location = "chat-room-login.php"; </script>';}}}}
?>
<h1>Chat Room Login or Sign-up</h1>
<div id='pw' style='position:absolute;top:110px;left:600px;width:350px;border:4px solid blue;background-color:#8aa;'><table border='0' cellspacing=0 cellpadding=6><tr><th style='font-size:24;text-align:center'>Sign Up</th></tr>
<form id='formpw' name="formpw" method="post" action="chat-room-login.php" onsubmit="return validatepassword()">
<tr><td><label for="User Name"><b>User Name: </b><input type="text" name="username" size="20" maxlength="20" value=""></label> </td></tr>
<tr><td><label for="Screen Name"><b>Screen Name: </b><input type="text" name="screen_name" size="20" maxlength="20" value=""></label> </td></tr>
<tr><td><label for="Password"><b>Password: </b><input type="password" name="upassword" size="20" maxlength="20" value=""></label> </td></tr>
<tr><td><label for="Email"><b>Email: </b><input type="text" name="email" size="25" maxlength="65" value=""></label> </td></tr>
<tr><td><label for="Please answer question"><b>Please answer question: </b><input type="text" name="captcha" size="16" maxlength="16" value=""></label></td></tr>
<tr><td> <IMG SRC="login-question.png" WIDTH=295 HEIGHT=36 BORDER=0></td></tr>
<tr><td><BR>
<input type="submit" value="Submit" name="register">
<input type="reset" value="Reset"></form></td></tr></table>
</div>
<div id='login' style='position:absolute;top:110px;left:100px;width:350px;border:4px solid blue;background-color:#8aa;'><table border='0' cellspacing=0 cellpadding=6><tr><th style='font-size:24;text-align:center'>Login</th></tr>
<form id='formlogin' name="formlogin" method="post" action="chat-room-login.php" onsubmit="return validatepasswordlogin()">
<tr><td><label for="User Name"><b>User Name: </b><input type="text" name="uname" size="20" maxlength="20" value=""></label> </td></tr>
<tr><td><label for="Password"><b>Password: </b><input type="password" name="upasswordlogin" size="20" maxlength="20" value=""></label> </td></tr>
<tr><td><BR>
<input type="submit" value="Submit" name="login">
<input type="reset" value="Reset"></form></td></tr></table>
</div>
<div id='dump' style='position:absolute;top:360px;left:100px;width:350px;border:4px solid blue;background-color:#8aa;'><table border='0' cellspacing=0 cellpadding=6><tr><th style='font-size:24;text-align:right'>Delete Account </th></tr>
<form id='formdump' name="formdump" method="post" action="chat-room-login.php" onsubmit="return validatedump()">
<tr><td><label for="User Name"><b>User Name: </b><input type="text" name="dumpname" size="20" maxlength="20" value=""></label> </td></tr>
<tr><td><label for="Password"><b>Password: </b><input type="password" name="dumppassword" size="20" maxlength="20" value=""></label> </td></tr>
<tr><td><BR>
<input type="submit" value="Submit" name="dumplogin">
<input type="reset" value="Reset"></form></td></tr></table>
</div>
</body>
</html>