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

 "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

 $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






	





Welcome
Logout
Members Area
Login/Register To Gain Access
Login
Register

login.php






	





Your Already Logged In. Return To Members Area
Login To Your Account
A Field Was Left Blank.
"; // 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 "
Unknown Error.
"; } }else{ // Username or password incorrect. echo "
Incorrect Username Or Password.
"; } } } ?>
Username: Password:

register.php






	





You've already got an account. Return To Members Area
Create An Account
A Field Was Left Blank.
"; }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 "
Username Already In Use.
"; }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 "
An Account Already Registered Has The Email ".$_POST['email_address'].".
"; }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 "
Successfully Registered.You can now login.
"; }else{ // If it couldnt insert user display error message. echo "
Unknown Error.
"; } } } } } ?>
Username: Password: Email Address:

logout.php






	





Logout Of Your Account
Successfully Logged Out
"; }else{ // If an error occured show error message. echo "
Unknown Error. Unable to logout.
"; } }else{ // If not logged in ?>
You are not logged in. Please login here

membersarea.php






	





Welcome To The Members AreaLogout
To check if someone is logged in. You can use the example below.
User ID: Username: Password: Email Address: IP Address: Session ID: Session: This usersystem tutorial was written by Peter Kelly of www.pk-tuts.co.uk
You are not logged in. Please login here

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.

Comments posted (1)

[...] 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 [...]

Write a comment

You must be logged in to post a comment.

Tutorials Written By Peter Kelly