PHP Tutorials

User login system

Most of us at times need to password protect areas of our site, heres a great way to have a user/login system...
1
I know most web sites now have features for their members. They may have email, skins of the site, members only areas, or any thing else. In this tutorial I will show you how to get skeleton of the user login working. The script will have 4 files. Two will let the user register and two will let the other two will have them log in. Before you start make sure you have mysql installed on your server. I wrote this script for PHP Version >= 4.2.0. If you are using an older version, I suggest that you download it from www.php.net. If you do not have a server of your own you can read my tutorial on this web site. Just press your browsers back button to get a list of all the php related tutorials. Click on Your Own Server.

Now that we are ready to begin. We will want to create a mysql table. We will need field for the ID#, User Name, and User Password. Here is the schema of my table:

CREATE TABLE user (
ID smallint(3) NOT NULL auto_increment,
Name varchar(30) NOT NULL default '',
Password varchar(32) NOT NULL default '',
PRIMARY KEY (ID),
UNIQUE KEY Name (Name)
)
TYPE=MyISAM;

Go ahead and create that table in what ever database you prefer. If have access to the Server, you can create the table through the MySQL command line. Next, we will make a config file for use to include in all the pages that need the database.

<?php
$User = "YourUserName";
$Pass = "YourUserPassword";
$Host = "YourDatabaseHost";
$DB = "YourMySQL Database";
$Table = "TableThatHoldsTheUserInfo";
?>

Replace the variables with there correct values and save it as common.php. This file will be included in all the pages that need to connect to the database. This is the most important file in the script. Make sure you save it as .php file, if you don't or save it as .inc or .txt or anything else, other people will be able to see your information.
2
What goes on when the user registers? A script inserts the users Name and Password into the database. First off we will need to create the basic form to let them do so.

<!doctype html public "-//W3C//DTD HTML 4.0 //EN">
<html>
<head>
<title>Login Signup</title>
</head>
<body>
<form action="register.php" method="POST"> What is your desired username? <input type="text" name="Name" size="20">
<br>
What is your password? <input type="password" value="password" name="Password">
<br>
<input type="submit" value="Create!">
</form>
</body>
</html>

You can layout the form how ever you want, but keep in mind that the Name and Password input fields need to be there. Once you have the form ready, save it as register.html. Now we need to create the registration script. All it will do is insert the data from the form into the database and tell the user that they are now registered.
<?php
/* Include the DB connection Parameters */
include("common.php");

/*Connect to the DB using the info in common.php*/
if(!($link_id = mysql_connect($Host, $User, $Pass))) die(mysql_erorr());
mysql_select_db($DB);

/*Here is where the actual work is done. We add slashes to the username to prevent errors in the query. Then we encrypt the password. This password is NEVER decryptable. Never, so users can have a sense of security. We insert, and then we say they are registered. The Period as joins the strings togther, so we can join the returns of fucntions to that string without creating a new variable foreach one.*/
$sql = "INSERT INTO " . $Table . " VALUES('', '" . addslashes($_POST['Name']) . "', '" . md5($_POST['Password']) . "')";
if(!($result = mysql_query($sql))) {
die(mysql_error());
} else {
/*You can redirect them instead of just giving them a link, to do this: you would replace the code below with header("location: login.html"); Be warned, you can't send headers after text is outputted, so if you wanted to have the message, and have them be forwareded, you would have to put the function ob_start() at the very first line of this file, and call ob_end_flush() at the very end.*/
echo "Your user account has been created!<br>";
echo "<a href=login.html>Continues</a> to the login page";
}
?>

Read the comments in the code if you don't understand. Now we need to create the login pages.
3
When the users logs in, there password and username are matched against a database. Just like before we will need a form to get the information from the user. Just like before, you can layout the form in anyway as long as the Name and Password values are there.
<!doctype html public "-//W3C//DTD HTML 4.0 //EN">
<html>
<head>
<title>Title here!</title>
</head>
<body>
<form method="post" action="login.php"> Enter your User Name <input type="text" name="Name" size="20">
<br>
Enter you Password <input type="password" name="Password" size="20">
<br>
<input type="submit" name="submit">
</form>
</body>
</html>

When you are ready, save this file as login.html.

Next we will create the login page. It will match there name and password against the ones stored in the database.
<?php
include("common.php");

if(!($link_id = mysql_connect($Host, $User, $Pass))) die(mysql_erorr());
mysql_select_db($DB);

/*This is were the actual log in takes place. We tell mysql to select the ID where the Name is exactly like the Name from the Form where is Password is exactly like the encryption values of the password from the form.*/

$sql = "SELECT ID FROM " . $Table . " WHERE Name='" . addslashes($_POST['Name']) . "' AND Password='" . md5($_POST['Password']) . "' LIMIT 1";

if(!($result = mysql_query($sql))) die(mysql_error());

/*This is were we check the result. We check to see how many rows were in the result of the query. If there is 1 one row in the result, that means there is one username with the right information, so that would mean they are logged in.*/
if(mysql_num_rows($result) == 1) {
/*Here we set a cookie that tells if the user has logged in and set it to last for a day. The cookie is used on the members page to check If they cookie is there they can see the page, if not they can't.*/

setcookie("LoggedIn, TRUE, time()+(3600 * 24));

/*You could also do the header() here just like I explained before.*/

echo "Continue to the <a href=members.php>Members</a> page.";
} else {
echo "Login failure";

}
?>

If you don't understand, read the comments in the code, they are very clear. Now we need to have a actual members page. This is quite simple. Create a page called members.php and put this code in it:

<?php
/*If the cookie isset then they are logged in, else the scripts dies and says they are not logged in.*/

if(!isset($_COOKIE['LoggedIn'])) die("You are not logged in!");

/*Your content goes here. If it is php, keep it above the ?>. If it is HTML code, put below the ?> or you will get errors*/

?>

Now that you have the files written, you can open up register.htm and register and go login to make sure that it works. I hope that my tutorial was easy to follow and clear. If you have any questions you can email me at z-team@attbi.com or contact me on www.neverside.com My user name is Adman.
This tutorial was by Adman, brought to you by Robouk, please post any questions in the forum. Thank you.
« BACK TO TUTORIALS