Home      Products & Services      Contact Us      Links

WebHatchers will design & develop your site for you.

Website Menu Heaven: menus, buttons, etc.

Send us your questions.

site search by freefind

SEO, Google, Privacy
   and Anonymity
Browser Insanity
Popups and Tooltips
Free Website Search
HTML Form Creator
Buttons and Menus
Image Uploading
Website Poll
IM and Texting
   or Not MySQL
Personal Status Boards
Content Management
Article Content
   Management Systems
Website Directory
   CMS Systems
Photo Gallery CMS
Forum CMS
Blog CMS
Customer Records
   Management CMS
Address Book CMS
Private Messaging CMS
Chat Room CMS
JavaScript Charts
   and Graphs

Free Personal Status Boards (PSB™)

Free Standard Free PSB

Free PSB Pro Version

Free Social PSB

Free Social PSB Plus (with Email)

Free Business PSB

Free Business PSB Plus (with Email)

PSB demo

Social PSB demo

Business PSB demo

So what's all this PSB stuff about?

Chart comparing business status boards

PSB hosting diagram

PSB Licence Agreement

Copyright © 2002 -
MCS Investments, Inc. sitemap

PSBs, social networking, social evolution, microcommunities, personal status boards
PSBs, social networking, business personal status boards
website design, ecommerce solutions
website menus, buttons, image rotators
Ez-Architect, home design software
the magic carpet and the cement wall, children's adventure book
the squirrel valley railroad, model railroad videos, model train dvds
the deep rock railroad, model railroad videos, model train dvds

Login for Private Messaging on Your Website

private messaging

This page is a tutorial on putting a private messaging (PM) login and registration page on your website. It uses sessions, both JavaScript and PHP input validation and input cleaning, PHP, MySQL, password hashing, and a simple captcha system. Users must use this Private Message Login page to login prior to getting to the various private messaging pages. Once you get to these pages, with the menu in the side bar you can send a message or check out your inbox or outbox, or delete messages from your inbox or outbox or logout. The screenshot above is the private message inbox.

The registration script has a special feature: a captcha. This stops most automatic spambots from registering and spamming your site. The way it works is that you see a text sentence that is really a hard-for-bots-to-read image and not a text string. It asks a question that's easy to answer if you are looking at the captcha but nearly impossible if you cannot see the image and come up with a good answer.

The script will allow either registering or logging in, whichever is appropriate. It will insist on passwords and usernames between 6 and 20 characters long. Let's check out the code. It starts with a PHP function: session_start(). This gets a session started. If the user succeeds at logging in or registering and gets to the various private messaging apps in the side menu (which get seen as soon as the login or registration succeeds), each app page will start by executing the following session script:




header('location: message-login.php');

// session logged

This just does what it ought to on each app page: continue the session and restart the session timeout clock which is set for 24 to 48 minutes, depending on the PHP installation directives. We then check the session variable "sessionid" which was saved at login. If it's not set, the user is sent to the login page after unsetting and destroying the session. If it is set, the user gets to continue the script since the else conditional leads only to a comment that does nothing, but says it all: "session logged." So the user is okay and good to go. As stated, the non-login pages will run the above script, but the login/registration script we're discussing on this page will get only session_start() and then a bit of session variable saving before the user is sent off to Private Message Sending Form.

Next we have the JavaScript input validators. The email script can handle nearly any email address provided it sticks with letters, numbers, hyphen and underline. Note that when bad input is entered, the user gets a message and the cursor jumps to the input box where the unacceptable input happened, due to dot notation and the focus() function. When the forms get submitted, an onsubmit event is what sends the action to these input filters.

Next we get ready to access the MySQL database by using the include with config.php in it. Then comes the password hashing function that employs both md5 and sha512 in a very tricky fashion. Then we create the MySQL database table messagemembers if it doesn't already exist. Here we store member data.

Now we have the registration script where we check the POSTed register flag which shows they submitted that form. If they didn't, the action jumps to checking whether they submitted the login form, and if not, the HTML forms are displayed. But if the register flag is set, we get two more POSTs into PHP variables: the username and the captcha answer. If the answer is wrong or empty, they are prompted to answer it and they are sent to the forms again. If the answer is right, the PHP input validation scripts are run and bad input sends them back to the forms because of the chain of else statements. Next the db is checked for the username entered and if it is found, the user will see "Username already in use."

If all went okay up to this point, the database table gets the new user's data inserted into it (after we run the hashing function, of course). This includes id, username, upassword, email, ip, date. Next, the user gets a "Welcome to this Website!" email sent to the email he or she provided. Then $_SESSION['sessionid'] = session_id() and $_SESSION['username'] = $U are used because the correct way to store and retrieve session variables is to use the PHP $_SESSION variable. Other ways are deprecated. Saving the session id and checking whether it is set in each app page is one of many ways to utilize sessions. We generally shy away from sessions because of their security vulnerabilities, but for private messaging we felt they were needed. Finally we close the MySQL db and give the new registrant the message "Thank you for registering."

Now we process the login script. Users either login or register on this login page and the code on this page handles either. If the login flag is set, we run the hashing function on the submitted password once we get the POSTed password and username. We check the database table for the entered username and if it cannot be found, the user sees the message "This user name does not exist. Please try again." Otherwise the entered password hash and the stored password hash are compared and if they match, the user is logged in and we load session variables with $_SESSION['sessionid'] = session_id() and $_SESSION['username'] = $U. Finally we close the MySQL db and send the user to Private Message Sending Form.

The forms are next. The only thing worth remarking on is the login-question.png image which is a graphics version of a saved text sentence that poses a question to the user as a captcha. This is for script security. Then there's the onsubmit events in both the login form and the registration form. We validate the input in both JavaScript and PHP because this allows us to reposition the cursor to the appropriate input box when faulty input is received, for user convenience, but at the same time provide extra security if someone tries to use the forms with JavaScript turned off.

Name this file message-login.php


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
<TITLE>Login For Site with Private Messaging</TITLE>
<meta name="description" content="Login For Site with Private Messaging">
<meta name="keywords" content="Login For Site with Private Messaging,Login Script,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;}
<script language="javascript">

function validatepassword(){

var ck_password = /^[A-Za-z0-9!@#$%^&*()_]{6,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_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!@#$%^&*()_]{6,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 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 messagemembers (
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(65) NOT NULL,


$U = $_POST['username'];
$L = $_POST['captcha'];if ($L<>"of"){
echo '<script language="javascript">alert("Please answer question."); window.location = "message-login.php"; </script>';


$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 = "message-login.php"; </script>';}

$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 = "message-login.php"; </script>';}

$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 = "message-login.php"; </script>';}

$memip = $_SERVER['REMOTE_ADDR'];
$date = date("d-m-Y");
$checkformembers = mysql_query("SELECT * FROM messagemembers WHERE username = '$U'");
if(mysql_num_rows($checkformembers) != 0){echo '<script language="javascript">alert("Username already in use. Please try again.")</script>;';



$create_member = mysql_query("INSERT INTO messagemembers (id, username, upassword, email, ip, date)
VALUES('','$U','$c','$email','$memip','$date')") or die(mysql_error());

$to = $email;
$subject = "Welcome to this Website!";
$message = "You've successfully registered as this Website member.\n\nYour user name is ".$U.".\n\nYou may now go to this Website.\n\nDon't give your password to anyone, but do save it somewhere safe.\n\nEnjoy this Website!\n\nRegards,\n\nthis Website management";
$headers = "From: ".$psbhostemailaddress."\r\nReply-To: ".$email;
$mail_sent = mail($to, $subject, $message, $headers);

$_SESSION['sessionid'] = session_id();
$_SESSION['username'] = $U;


echo '<BR><BR><script language="javascript">alert("Thank you for registering.");window.location = "send-message-form.php";</script>';}}}

$U = $_POST['uname'];
$P = $_POST['upasswordlogin'];$upassword=$P;mix();

$check_user_data = mysql_query("SELECT * FROM messagemembers 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);


$get_user_data = mysql_fetch_array($check_user_data);

if($Z != $c || !isset($_POST['login']))
{echo '<script language="javascript">alert("Username/password pair is invalid. Please try again.")</script>;';unset($U);unset($P);


$_SESSION['sessionid'] = session_id();
$_SESSION['username'] = $U;


echo '<script language="javascript">window.location = "send-message-form.php";</script>';}}}


<h1>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="message-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>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr>
<tr><td><label for="Password"><b>Password: &nbsp;&nbsp;&nbsp;</b><input type="password" name="upassword" size="20" maxlength="20" value=""></label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr>
<tr><td><label for="Email"><b>Email: &nbsp;&nbsp;&nbsp;</b><input type="text" name="email" size="25" maxlength="65" value=""></label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</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>&nbsp;&nbsp;&nbsp;&nbsp;<IMG SRC="login-question.png" WIDTH=295 HEIGHT=36 BORDER=0></td></tr>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" value="Submit" name="register">
<input type="reset" value="Reset"></form></td></tr></table>

<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="message-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>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr>
<tr><td><label for="Password"><b>Password: &nbsp;&nbsp;&nbsp;</b><input type="password" name="upasswordlogin" size="20" maxlength="20" value=""></label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" value="Submit" name="login">
<input type="reset" value="Reset"></form></td></tr></table>