Usersystem Part 1
Posted by Pete | Posted in PHP Tutorials | Posted on 28-09-2009-05-2008
1
Well after getting side tracked yet again I have written a user system for the users of PK-Tuts. In this part of the user system we will learn how to login and register will will also build some of the basic functions to check if you are logged in and logout. I will be expanding the user system in multiple parts so keep checking back.
First create a MySQL database, user name and password then go to PHPMyAdmin and run the following sql statement.
CREATE TABLE IF NOT EXISTS `sessions` (
`id` int(50) NOT NULL AUTO_INCREMENT,
`sess_id` varchar(200) NOT NULL,
`uid` varchar(50) NOT NULL,
`logged` varchar(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(50) NOT NULL AUTO_INCREMENT,
`username` varchar(35) NOT NULL,
`password` varchar(90) NOT NULL,
`email` varchar(90) NOT NULL,
`ip` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
This will create both the users table and sessions.
I have commented all the PHP code below is the actual code but I have compiled all pages into a zip file which is available at the link at the bottom of this post.
Put the following 4 images in a folder called images
http://www.pk-tuts.co.uk/wp-content/uploads/2009/09/images/login.jpg
http://www.pk-tuts.co.uk/wp-content/uploads/2009/09/images/logout.jpg
http://www.pk-tuts.co.uk/wp-content/uploads/2009/09/images/membersarea.jpg
http://www.pk-tuts.co.uk/wp-content/uploads/2009/09/images/register.jpg
stylesheet.css
body { font-family:Arial, Helvetica, sans-serif; background-color: #006699; } a { color:white; } #select_btn_div { margin: 0 auto 10px; width: 440px; } #btn { border: 3px #2B65BD solid; } #selection_header { color: #FFFFFF; font-weight:bold; font-size:x-large; text-align:center; margin-top: 20px; margin-bottom: 20px; } #register_form { font-family: Arial, Helvetica, sans-serif; color: white; margin: 0 auto 10px; width: 440px; font-size: 10pt; } #register_form_field { font-family: Arial, Helvetica, sans-serif; font-size: 10pt; vertical-align: middle; padding: 0 0 0 0; margin-top: 2; border: thin #CCFFFF solid; } #error_msg { border: thing #950000 solid; text-align: center; background-color:#FF9B9B; color:red; } #success_msg { border: thing #006600 solid; text-align: center; background-color: #A6FFA6; color:lime; } #members_left { width: 395px; margin-right: 20px; float:left; color: white; text-align:center; } #members_right { width: 400px; float:left; color: white; }
configuration.php
<?php /** * @author Peter Kelly * @project Usersystem Part 1 */ /** DATABASE CONNECTION INFORMATION **/ // The information below is here to provide for the database connection at the bottom of this configuration file. // We are using defines. I will be covering a tutorial on at www.pk-tuts.co.uk soon. define("DATABASE_LOCATION", "localhost"); define("DATABASE_USERNAME", ""); define("DATABASE_PASSWORD", ""); define("DATABASE_NAME", ""); /** FILE LOCATIONS **/ // This is just a little addition so you can move the locations of the images folder, and stylesheet etc. $locations = array("images_folder" => "images/", "stylesheet" => "stylesheet.css"); /** CHECK FILE LOCATIONS **/ // Check if the file locations actually exist. if(!file_exists($locations['images_folder'])){die("Images Folder Not Present");} if(!file_exists($locations['stylesheet'])){die("StyleSheet Not Present");} /** CONNECT TO DATABASE **/ // If we cant connect to the database server with the username and password provided. Stop and show error. // Once connected If we can not select the database name provided then stop and show error. $conn = mysql_connect(DATABASE_LOCATION,DATABASE_USERNAME,DATABASE_PASSWORD); if (!$conn) die ("Could not connect MySQL Server With Username And Password"); mysql_select_db(DATABASE_NAME,$conn) or die ("Could Not Open Database"); /** INCLUDE FUNCTIONS **/ // The functions page included a lot of important functions which are required to use this usersystem. // So to save having to type it out on every page we will just include it in the configuration file which is also included on every page. include("functions.php"); ?>
functions.php
<?php /** * @author Peter Kelly * @project Usersystem Part 1 * @copyright 2009 */ function protection($field,$encrypt=false) // Start Of Function. { if (empty($field)) // Checks if $field is empty. { $return[error] = "Value Empty"; // If $field is found to be empty it will return an error message. } else { if (is_array($field)) // Checks if $field is an array or not. { // If it is an array then carry on. foreach($field as $key => $value){ // Carry out the foreach on the $field assigning the key and value of the array to $key and $value. $key = strip_tags($key); // Remove any tags from the field $value = strip_tags($value); // Remove any tags from the field $return[$key] = htmlentities($value, ENT_QUOTES); // Convert all applicable characters to HTML entities } } else // If $field isnt an array carry out the following. { $field = strip_tags($field); // Remove any tags from the field. $return = htmlentities($field, ENT_QUOTES); // Convert all applicable characters to HTML entities. } } return $return; // Return $return } function logged_in(){ $sess_id = protection($_COOKIE['PHPSESSID']); // Remove any injection and bugout stuff from the session // Retrieve the sessions tables wheres the session id above matches the session id in the sessions table $conn = mysql_connect(DATABASE_LOCATION,DATABASE_USERNAME,DATABASE_PASSWORD); mysql_select_db(DATABASE_NAME,$conn); $sess_check = mysql_query("SELECT * FROM `sessions` WHERE `sess_id` = '".$sess_id."' && `logged` = '0'"); // If there is no session in the table where they are not logged in, show them as not logged in if(mysql_num_rows($sess_check)){ // Check if there is a row in the table. $s = mysql_fetch_array($sess_check); // Retrieve the data from the tables. $uinfo = mysql_query("SELECT * FROM `users` WHERE `id` = '".$s['uid']."'"); // Retrieve the users table where the uid matches the uid in the sessions table $u = mysql_fetch_array($uinfo); // Retrieve the data from the tables. // Put the data into an array to be returned. $return = array("session_id" => $s['id'], "session_sessid" => $s['sess_id'], "user_id" => $u['id'], "username" => $u['username'], "password" => $u['password'], "email" => $u['email'], "ip" => $u['ip']); // Return the array return $return; }else{ // Return nothing return false; } } function check_phpsessid(){ session_start(); if(empty($_COOKIE['PHPSESSID'])){ die("Your cookies are disabled. Please enable them before using this usersystem."); } } ?>
index.php
<?php /** Selection Page **/ // First we must start off the sessions session_start(); // Then include the configuration file which has the database connection and locations. include("configuration.php"); ?> <!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" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Selection Page</title> <link rel="stylesheet" type="text/css" href="<?php echo $locations['stylesheet'] ?>" /> </head> <body> <?php if($loggedin = logged_in()){ ?> <div id="selection_header">Welcome <?php echo $loggedin['username'] ?></div> <div id="select_btn_div"><a href="logout.php"><img id="btn" src="<?php echo $locations['images_folder'] ?>logout.jpg" alt="Logout" /></a></div> <div id="select_btn_div"><a href="membersarea.php"><img id="btn" src="<?php echo $locations['images_folder'] ?>membersarea.jpg" alt="Members Area" /></a></div> <?php }else{ ?> <div id="selection_header">Login/Register To Gain Access</div> <div id="select_btn_div"><a href="login.php"><img id="btn" src="<?php echo $locations['images_folder'] ?>login.jpg" alt="Login" /></a></div> <div id="select_btn_div"><a href="register.php"><img id="btn" src="<?php echo $locations['images_folder'] ?>register.jpg" alt="Register" /></a></div> <?php } ?> </body> </html>
login.php
<?php /** Selection Page **/ // First we must start off the sessions session_start(); ob_start(); // Then include the configuration file which has the database connection and locations. include("configuration.php"); ?> <!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" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Login</title> <link rel="stylesheet" type="text/css" href="stylesheet.css" /> </head> <body> <?php if($loggedin = logged_in()){ // Check if they are logged in ?> <div id="selection_header">Your Already Logged In.<br /><a href="membersarea.php"> Return To Members Area</a></div> <?php }else{ // If not logged in ?> <div id="selection_header">Login To Your Account</div> <?php if($_POST['submit']){ // Check if submit button has been pressed. /** CHECK COOKIES **/ echo check_phpsessid(); $_POST = protection($_POST); // Protect the $_POST variable. $_GET = protection($_GET); // Protect the $_GET variable. if(empty($_POST['username']) || empty($_POST['password'])){ // Check if the form fields are empty or not. echo "<div id='error_msg'>A Field Was Left Blank.</div>"; // If there empty show error message. }else{ $chkuser = mysql_query("SELECT * FROM `users` WHERE `username` = '".$_POST['username']."' && `password` = '".md5($_POST['password'])."'"); // Check if the username and password are correct. if(mysql_num_rows($chkuser)){ // Check if they are correct $vcu = mysql_fetch_array($chkuser); // Get the information $results = mysql_query("INSERT into `sessions` (`sess_id`, `uid`, `logged`) values ('".$_COOKIE['PHPSESSID']."', '".$vcu['id']."', '0');"); // Insert the session id and user id into the sessions table to create the login. if($results){ // If it submitted it then success. if(empty($_GET['r'])){ // If $_GET['r'] is blank redirect the user to index.php after login if not redirect the user to the url indicated in login.php?r=http://www.google.com header("Location: index.php"); }else{ header("Location: ".$_GET['r']); } }else{ // If couldnt submit into sessions table then show error message echo "<div id='error_msg'>Unknown Error.</div>"; } }else{ // Username or password incorrect. echo "<div id='error_msg'>Incorrect Username Or Password.</div>"; } } } ?> <div id="register_form"> <form method="post"> Username: <input id="register_form_field" name="username" type="text"><br /> Password: <input id="register_form_field" name="password" type="password"><br /> <input id="register_form_field" name="submit" type="submit" value="Register"></form> </div> <?php } ?> </body> </html>
register.php
<?php /** Selection Page **/ // First we must start off the sessions session_start(); // Then include the configuration file which has the database connection and locations. include("configuration.php"); ?> <!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" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Register An Account</title> <link rel="stylesheet" type="text/css" href="stylesheet.css" /> </head> <body> <?php if($loggedin = logged_in()){ // Check if they are logged in ?> <div id="selection_header">You've already got an account.<br /><a href="membersarea.php"> Return To Members Area</a></div> <?php }else{ // If not logged in ?> <div id="selection_header">Create An Account</div> <?php if($_POST['submit']){ // Check if submit button has been pressed $_POST = protection($_POST); // Protect the $_POST variable. if(empty($_POST['username']) || empty($_POST['password']) || empty($_POST['email_address'])){ echo "<div id='error_msg'>A Field Was Left Blank.</div>"; }else{ $ucheck = mysql_query("SELECT * FROM `users` WHERE `username` = '".$_POST['username']."'"); // Check if there is an account with the username posted. if(mysql_num_rows($ucheck)){ // If there is show error. echo "<div id='error_msg'>Username Already In Use.</div>"; }else{ // If not carry on. $echeck = mysql_query("SELECT * FROM `users` WHERE `email` = '".$_POST['email_address']."'"); // Check if an account has the email address posted. if(mysql_num_rows($echeck)){ // If there is show error. echo "<div id='error_msg'>An Account Already Registered Has The Email ".$_POST['email_address'].".</div>"; }else{ // If not carry on. $encrypted_password = md5($_POST['password']); // Encrypt the password through MD5 $ip_address = $_SERVER['REMOTE_ADDR']; // Get the persons IP Address // Insert the user into the users table. $results = mysql_query("INSERT into `users` (`username`, `password`, `email`, `ip`) values ('".$_POST['username']."', '".$encrypted_password."', '".$_POST['email_address']."', '".$ip_address."');"); if($results){ // If it added the user display success message echo "<div id='success_msg'>Successfully Registered.<br />You can now <a href='login.php'>login</a>.</div>"; }else{ // If it couldnt insert user display error message. echo "<div id='error_msg'>Unknown Error.</div>"; } } } } } ?> <div id="register_form"> <form method="post"> Username: <input id="register_form_field" name="username" type="text"><br /> Password: <input id="register_form_field" name="password" type="password"><br /> Email Address: <input id="register_form_field" name="email_address" type="text"><br /> <input id="register_form_field" name="submit" type="submit" value="Register"></form> </div> <?php } ?> </body> </html>
logout.php
<?php /** Selection Page **/ // First we must start off the sessions session_start(); ob_start(); // Then include the configuration file which has the database connection and locations. include("configuration.php"); ?> <!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" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Logout</title> <link rel="stylesheet" type="text/css" href="stylesheet.css" /> </head> <body> <?php if($loggedin = logged_in()){ // Check if they are logged in ?> <div id="selection_header">Logout Of Your Account</div> <?php $update = mysql_query("UPDATE `sessions` SET `logged` = '1' WHERE `id` = '".$loggedin['session_id']."'"); // Update the current session to log the person out. if($update){ // If it successfully logged the person out then show success message. echo "<div id='success_msg'>Successfully Logged Out</div><div id='selection_header'><a href='index.php'>Return Here</a></div>"; }else{ // If an error occured show error message. echo "<div id='error_msg'>Unknown Error. Unable to logout.</div>"; } }else{ // If not logged in ?> <div id="selection_header">You are not logged in.<br /> Please login <a href="login.php">here</a></div> <?php } ?> </body> </html>
membersarea.php
<?php /** Selection Page **/ // First we must start off the sessions session_start(); ob_start(); // Then include the configuration file which has the database connection and locations. include("configuration.php"); ?> <!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" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Members Area</title> <link rel="stylesheet" type="text/css" href="stylesheet.css" /> </head> <body> <?php if($loggedin = logged_in()){ // Check if they are logged in ?> <div id="selection_header">Welcome <?php echo $loggedin['username']; ?> To The Members Area<br /><a href="logout.php">Logout</a></div> <div id="content"> <div id="members_left"> To check if someone is logged in. You can use the example below. <textarea name="loggedin_check" style="width: 390px; height: 200px"><?php session_start(); if($loggedin = logged_in()){ echo "Logged In"; }else{ echo "Not Logged In"; } ?></textarea> </div> <div id="members_right"> User ID: <?php echo $loggedin['user_id']; ?><br /> Username: <?php echo $loggedin['username']; ?><br /> Password: <?php echo $loggedin['password']; ?><br /> Email Address: <?php echo $loggedin['email']; ?><br /> IP Address: <?php echo $loggedin['ip']; ?><br /> Session ID: <?php echo $loggedin['session_id']; ?><br /> Session: <?php echo $loggedin['session_sessid']; ?><br /> <br /> This usersystem tutorial was written by Peter Kelly of www.pk-tuts.co.uk </div> </div> <?php }else{ // If not logged in ?> <div id="selection_header">You are not logged in.<br /> Please login <a href="login.php">here</a></div> <?php } ?> </body> </html>
If you want to download the files and images you can download it at
http://www.pk-tuts.co.uk/wp-content/uploads/2009/09/Usersystem-Part-1.zip.
Please this is only the starter for the user system I am planning on developing it a lot further and posting all tutorials on here. But if you like this or have any problems please leave a comment.
Edit: Minor Bug fixed in both the tutorial and upload.



[...] available for use . This part of the usersystem is the next part to the part 1 which can be found here. In this part we will focus on creating a ranking system so we can distinguish who is an [...]