Making A Cool Login System With PHP, MySQL & jQuery
Introduction
Today we are making a cool & simple login / registration system. It will give you the ability to easily create a member-only area on your site and provide an easy registration process.
It is going to be PHP driven and store all the registrations into a MySQL database.
To add the needed flair, we are using the amazing sliding jQuery panel, developed by Web-kreation.
Step 1 – MySQL
First we have to create the table that will hold all the registrations. This code is available in table.sql.
table.sql
-- -- Table structure for table `tz_members` -- CREATE TABLE `tz_members` ( `id` int(11) NOT NULL auto_increment, `usr` varchar(32) collate utf8_unicode_ci NOT NULL default '', `pass` varchar(32) collate utf8_unicode_ci NOT NULL default '', `email` varchar(255) collate utf8_unicode_ci NOT NULL default '', `regIP` varchar(15) collate utf8_unicode_ci NOT NULL default '', `dt` datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (`id`), UNIQUE KEY `usr` (`usr`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Notice that we’ve defined the id as an integer with auto_increment – it is automatically assigned to every site member. Also, we’ve defined usr as an unique key – no two users with the same usernames are allowed.
We later use this in the registration to determine whether the username has been taken.
After you create the table, do not forget to fill in your database credentials in connect.php so you can run the demo on your own server.
Step 2 – XHTML
First, we have to incorporate Web-kreation’s form into our page.
demo.php
<!-- Panel --> <div id="toppanel"> <div id="panel"> <div class="content clearfix"> <div class="left"> <h1>The Sliding jQuery Panel</h1> <h2>A register/login solution</h2> <p class="grey">You are free to use this login and registration system in you sites!</p> <h2>A Big Thanks</h2> <p class="grey">This tutorial was built on top of <a href="http://web-kreation.com/index.php/tutorials/nice-clean-sliding-login-panel-built-with-jquery" title="Go to site">Web-Kreation</a>'s amazing sliding panel.</p> </div> <?php if(!$_SESSION['id']): // If you are not logged in ?> <div class="left"> <!-- Login Form --> <form class="clearfix" action="" method="post"> <h1>Member Login</h1> <?php if($_SESSION['msg']['login-err']) { echo '<div class="err">'.$_SESSION['msg']['login-err'].'</div>'; unset($_SESSION['msg']['login-err']); // This will output login errors, if any } ?> <label class="grey" for="username">Username:</label> <input class="field" type="text" name="username" id="username" value="" size="23" /> <label class="grey" for="password">Password:</label> <input class="field" type="password" name="password" id="password" size="23" /> <label><input name="rememberMe" id="rememberMe" type="checkbox" checked="checked" value="1" /> Remember me</label> <div class="clear"></div> <input type="submit" name="submit" value="Login" class="bt_login" /> </form> </div> <div class="left right"> <!-- Register Form --> <form action="" method="post"> <h1>Not a member yet? Sign Up!</h1> <?php if($_SESSION['msg']['reg-err']) { echo '<div class="err">'.$_SESSION['msg']['reg-err'].'</div>'; unset($_SESSION['msg']['reg-err']); // This will output the registration errors, if any } if($_SESSION['msg']['reg-success']) { echo '<div class="success">'.$_SESSION['msg']['reg-success'].'</div>'; unset($_SESSION['msg']['reg-success']); // This will output the registration success message } ?> <label class="grey" for="username">Username:</label> <input class="field" type="text" name="username" id="username" value="" size="23" /> <label class="grey" for="email">Email:</label> <input class="field" type="text" name="email" id="email" size="23" /> <label>A password will be e-mailed to you.</label> <input type="submit" name="submit" value="Register" class="bt_register" /> </form> </div> <?php else: // If you are logged in ?> <div class="left"> <h1>Members panel</h1> <p>You can put member-only data here</p> <a href="registered.php">View a special member page</a> <p>- or -</p> <a href="?logoff">Log off</a> </div> <div class="left right"> </div> <?php endif; // Closing the IF-ELSE construct ?> </div> </div> <!-- /login --> <!-- The tab on top --> <div class="tab"> <ul class="login"> <li class="left"> </li> <li>Hello <?php echo $_SESSION['usr'] ? $_SESSION['usr'] : 'Guest';?>!</li> <li class="sep">|</li> <li id="toggle"> <a id="open" class="open" href="#"><?php echo $_SESSION['id']?'Open Panel':'Log In | Register';?></a> <a id="close" style="display: none;" class="close" href="#">Close Panel</a> </li> <li class="right"> </li> </ul> </div> <!-- / top --> </div> <!--panel -->
At several places in this code, there are some PHP operators that check whether $_SESSION[‘usr’] or$_SESSION[‘id’] are defined. This is true only if the page visitor is logged in the site, which allows us to show specific content to site members. We will cover it in detail in a moment.
After the form, we put the rest of the page.
<div class="pageContent"> <div id="main"> <div class="container"> <h1>A Cool Login System</h1> <h2>Easy registration management with PHP & jQuery</h2> </div> <div class="container"> <p>This is a ...</p> <div class="clear"></div> </div> </div>
Nothing special here. Lets continue with the PHP backend.
Step 3 – PHP
It is time to convert the form into a complete registration and login system. To achieve it, we will need more than the usual amount of PHP. I’ll divide the code into two parts.
If you plan to add more code, it would be a good idea to split it into several files which are included when needed. This aids the development of large projects and allows code reuse in different parts of a site.
But lets see how we’ve done it here.
demo.php
define('INCLUDE_CHECK',true); require 'connect.php'; require 'functions.php'; // Those two files can be included only if INCLUDE_CHECK is defined session_name('tzLogin'); // Starting the session session_set_cookie_params(2*7*24*60*60); // Making the cookie live for 2 weeks session_start(); if($_SESSION['id'] && !isset($_COOKIE['tzRemember']) && !$_SESSION['rememberMe']) { // If you are logged in, but you don't have the tzRemember cookie (browser restart) // and you have not checked the rememberMe checkbox: $_SESSION = array(); session_destroy(); // Destroy the session } if(isset($_GET['logoff'])) { $_SESSION = array(); session_destroy(); header("Location: demo.php"); exit; } if($_POST['submit']=='Login') { // Checking whether the Login form has been submitted $err = array(); // Will hold our errors if(!$_POST['username'] || !$_POST['password']) $err[] = 'All the fields must be filled in!'; if(!count($err)) { $_POST['username'] = mysql_real_escape_string($_POST['username']); $_POST['password'] = mysql_real_escape_string($_POST['password']); $_POST['rememberMe'] = (int)$_POST['rememberMe']; // Escaping all input data $row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM tz_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'")); if($row['usr']) { // If everything is OK login $_SESSION['usr']=$row['usr']; $_SESSION['id'] = $row['id']; $_SESSION['rememberMe'] = $_POST['rememberMe']; // Store some data in the session setcookie('tzRemember',$_POST['rememberMe']); // We create the tzRemember cookie } else $err[]='Wrong username and/or password!'; } if($err) $_SESSION['msg']['login-err'] = implode('<br />',$err); // Save the error messages in the session header("Location: demo.php"); exit; }
Here the tzRemember cookie acts as a control whether we should log-off users that have not marked the “remember me” checkbox. If the cookie is not present (due to browser restart) and the visitor has not checked the remember me option, we destroy the session.
The session itself is kept alive for two weeks (as set by session_set_cookie_params).
Lets see the second part of demo.php.
else if($_POST['submit']=='Register') { // If the Register form has been submitted $err = array(); if(strlen($_POST['username'])<4 || strlen($_POST['username'])>32) { $err[]='Your username must be between 3 and 32 characters!'; } if(preg_match('/[^a-z0-9\-\_\.]+/i',$_POST['username'])) { $err[]='Your username contains invalid characters!'; } if(!checkEmail($_POST['email'])) { $err[]='Your email is not valid!'; } if(!count($err)) { // If there are no errors $pass = substr(md5($_SERVER['REMOTE_ADDR'].microtime().rand(1,100000)),0,6); // Generate a random password $_POST['email'] = mysql_real_escape_string($_POST['email']); $_POST['username'] = mysql_real_escape_string($_POST['username']); // Escape the input data mysql_query(" INSERT INTO tz_members(usr,pass,email,regIP,dt) VALUES( '".$_POST['username']."', '".md5($pass)."', '".$_POST['email']."', '".$_SERVER['REMOTE_ADDR']."', NOW() )"); if(mysql_affected_rows($link)==1) { send_mail( 'demo-test@tutorialzine.com', $_POST['email'], 'Registration System Demo - Your New Password', 'Your password is: '.$pass); $_SESSION['msg']['reg-success']='We sent you an email with your new password!'; } else $err[]='This username is already taken!'; } if(count($err)) { $_SESSION['msg']['reg-err'] = implode('<br />',$err); } header("Location: demo.php"); exit; } $script = ''; if($_SESSION['msg']) { // The script below shows the sliding panel on page load $script = ' <script type="text/javascript"> $(function(){ $("div#panel").show(); $("#toggle a").toggle(); }); </script>'; }
We store all the encountered errors in an $err array, which is later assigned to a $_SESSION variable. This allows it to be accessible after a browser redirect.
You may have noticed on some sites, that when you submit a form and later refresh the page, the data is sent all over again. This could become problematic as it could lead to a double registrations and unnecessary server load.
We use the header function to prevent this, by redirecting the browser to the same page. This starts a fresh view of the page, without the browser associating it with a form submit. The result is that, on page refresh, no data is sent.
But as we use $_SESSION to store all the encountered errors it is important that we unset these variables, once we show the errors to the user. Otherwise they will be shown on every page view (the highlighted lines on the XHTML part of the tutorial).
Also notice how we create an additional script (lines 60-70 of the second part of the PHP code) which shows the panel on page load, so that the messages are visible to the user.
Now lets take a look at the CSS.
Step 4 – CSS
The sliding panel comes with its own style sheet. This means we are only left with creating the page styles.
demo.css
body,h1,h2,h3,p,quote,small,form,input,ul,li,ol,label{ /* The reset rules */ margin:0px; padding:0px; } body{ color:#555555; font-size:13px; background: #eeeeee; font-family:Arial, Helvetica, sans-serif; width: 100%; } h1{ font-size:28px; font-weight:bold; font-family:"Trebuchet MS",Arial, Helvetica, sans-serif; letter-spacing:1px; } h2{ font-family:"Arial Narrow",Arial,Helvetica,sans-serif; font-size:10px; font-weight:normal; letter-spacing:1px; padding-left:2px; text-transform:uppercase; white-space:nowrap; margin-top:4px; color:#888888; } #main p{ padding-bottom:8px; } .clear{ clear:both; } #main{ width:800px; /* Centering it in the middle of the page */ margin:60px auto; } .container{ margin-top:20px; background:#FFFFFF; border:1px solid #E0E0E0; padding:15px; /* Rounded corners */ -moz-border-radius:20px; -khtml-border-radius: 20px; -webkit-border-radius: 20px; border-radius:20px; } .err{ color:red; } .success{ color:#00CC00; } a, a:visited { color:#00BBFF; text-decoration:none; outline:none; } a:hover{ text-decoration:underline; } .tutorial-info{ text-align:center; padding:10px; }
Step 5 – jQuery
The sliding panel comes with its own jQuery files.
demo.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <!-- PNG FIX for IE6 --> <!-- http://24ways.org/2007/supersleight-transparent-png-in-ie6 --> <!--[if lte IE 6]> <script type="text/javascript" src="login_panel/js/pngfix/supersleight-min.js"></script> <![endif]--> <script src="login_panel/js/slide.js" type="text/javascript"></script> <?php echo $script; ?>
First we include the jQuery library from Google’s CDN. Later comes a special fix for IE6 PNG transparency issues and lastly the panel’s script is included.
At the bottom of the page is the $script variable – it shows the panel on page load if needed.
With this our cool login system is complete!
Conclusion
Today we learned how to use a fantastic form component and turn it into a functional log in / registration system.
You are free to built upon this code and modify it any way you see fit.