.
Tutorial
Avatar

Create a simple login system

By Remco on 2009-05-07
Views: 3652

Introduction

This 7 step tutorial is going to teach you how to create a login system by using PHP/MYSQL.
( When copy and pasting scripts from this tutorial, please notice that you have to change the URL and database settings to your own. )

Required files for this tutorial:

  • connect.php
  • login.php
  • logout.php
  • actions.php
  • create.php
  • register.php
  • index.php


Step 1 - Creating the database and user table.

To create a login system you must store your users somewhere.
The easiest way to do this is to just store them in your database.

We will provide you with the script you need to create the database + all tables needed for this tutorial.
Copy and paste the code into the file: create.php


Code:


<?php

$host 
"localhost"// mysql host  
$dbuser "root"// mysql username  
$pass "pass"// mysql password  

mysql_connect($host,$dbuser,$pass)or die('Could not connect: '.mysql_error());  

$databasename "database"
 
mysql_query("CREATE DATABASE `".$databasename."` ");  

// Create the user table
// username and password will be primary key because they will identify the user.
mysql_query(
CREATE TABLE `"
.$databasename."`.`users`( 
username varchar(255), 
password varchar(255),
firstname varchar(255), 
lastname varchar(255), 
email varchar(255), 
PRIMARY KEY (username,password) 
)"
);

?>



Once pasted into your file, change the database details to your own to make this script work.
Please run this script, if you don't get an error it means your database has been created.

Step 2 - Create the connect file

To interact with your database we're going to create the connect file, please copy and paste the following code into connect.php


Code:


<?php

$host 
"localhost"// mysql host  
$dbuser "root"// mysql username  
$pass "pass"// mysql password
$databasename "database"// database name  

mysql_connect($host,$dbuser,$pass)or die('Could not connect: '.mysql_error());  
mysql_select_db($databasename) or die(mysql_error());

?>




Now this is done we can start creating a register form to register the users to the database.
Why make a register form?

Storing the personal data of a user has got to happen safely.
If your database gets hacked, you don't want your users details to be liturally offered to the hacker. Besides, it's none of your business what other people their passwords are... So we use a form to let the user fill in their information.
As we save the information we can make the password unreadable for people.
More information about this later.

Step 3 - Register form

We're going to create the register form.
In this form we will let the user fill in all the details we need.

copy and paste this code into register.php:


Code:


<?php 

echo 
<form action='actions.php' method='post'>
<table cellpadding='2' cellspacing='0'>
    <tr>
        <td style='width:100px;font-family:Verdana;font-weight:bold;font-size:12px;'>
            Username
        </td>
        <td>
            <input type='text' name='f_username'>
        </td>
    </tr>
    <tr>
        <td style='width:100px;font-family:Verdana;font-weight:bold;font-size:12px;'>
            Password
        </td>
        <td>
            <input type='password' name='f_password'>
        </td>
    </tr>
    <tr>
        <td style='width:100px;font-family:Verdana;font-weight:bold;font-size:12px;'>
            First name
        </td>
        <td>
            <input type='text' name='f_fname'>
        </td>
    </tr>
    <tr>
        <td style='width:100px;font-family:Verdana;font-weight:bold;font-size:12px;'>
            Last name
        </td>
        <td>
            <input type='text' name='f_sname'>
        </td>
    </tr>
    <tr>
        <td style='width:100px;font-family:Verdana;font-weight:bold;font-size:12px;'>
            E-mail adress
        </td>
        <td>
            <input type='text' name='f_email'>
        </td>
    </tr>
    <tr>
        <td style='width:100px;font-family:Verdana;font-weight:bold;font-size:12px;'>
                
        </td>
        <td>
            <input type='submit' name='f_save' value='Save'>
        </td>
    </tr>
</table>
</form> "


// As you can see here.. the actions we are going to perform will be made in actions.php 
?>



The form should look like this:
register.jpg

Because the actions will be performed in actions.php we're gonna get the actions.php up to put the actions in.

Please copy and paste the following code into actions.php.


Code:


<?php

include('connect.php');

if(
$_POST['f_save'])
{
    
// First we check if all fields are not empty.
    
if(!empty($_POST['f_username']) 
    && !empty(
$_POST['f_password']) 
    && !empty(
$_POST['f_fname']) 
    && !empty(
$_POST['f_sname']) 
    && !empty(
$_POST['f_email']))
    {
      
// If not empty we will execute this code.

      // Here we will convert the password to an md5 encrypted code.
      
$password md5($_POST['f_password']);

      if(!
mysql_query("INSERT INTO users 
      (username,password,firstname,lastname,email) 
      VALUES('"
.$_POST['f_username']."',
      '"
.$password."',
      '"
.$_POST['f_fname']."',
      '"
.$_POST['f_sname']."',
      '"
.$_POST['f_email']."') "))
      {
        echo 
"There was an error tryign to write the information to the database.";
      }
      else
      {
        echo 
$_POST['f_username']." has succesfully been added.";
      }
    }
    else
    {
       
// Not all information has been given.. you will automaticly 
       // return to the register page.
       
header("Location: ".$_SERVER['HTTP_REFERER']." ");
    }
}

?>




Now we have the form and the actions.. so it's time to run register.php by browsing to it: www.domain.com/register.php
If everything has been filled in correctly.. the user will be added,
so now we need the login form.

Step 5 - Login form

The login form will be made out of two text fields and a submit button.
Why?
Because the username and the password are the only two keys that make the user a unique user.
So copy and paste the follwing code into login.php


Code:


<?php 
session_start
(); 

echo

<form action='actions.php' method='post'>
<table cellpadding='2' cellspacing='0'>
    <tr>
        <td style='width:100px;font-family:Verdana;font-weight:bold;font-size:12px;'>
            Username
        </td>
        <td>
            <input type='text' name='f_username'>
        </td>
    </tr>
    <tr>
        <td style='width:100px;font-family:Verdana;font-weight:bold;font-size:12px;'>
            Password
        </td>
        <td>
            <input type='password' name='f_password'>
        </td>
    </tr>
    <tr>
        <td style='width:100px;font-family:Verdana;font-weight:bold;font-size:12px;'>
                
        </td>
        <td>
            <input type='submit' name='f_login' value='login'>
        </td>
    </tr>
</table>
</form>
<br>"
.$_SESSION['login_error']; 

?>



The form should look like this:
login.jpg

Just like the register form the actions will be performed in actions.php

To make all actions work replace all content of actions.php with:


Code:


<?php
session_start
();// We need the session to keep the user logged in.
include('connect.php'); // We need to connection to execute queries

if($_POST['f_save'])
{
    
// First we check if all fields are not empty.
    
if(!empty($_POST['f_username']) 
    && !empty(
$_POST['f_password']) 
    && !empty(
$_POST['f_fname']) 
    && !empty(
$_POST['f_sname']) 
    && !empty(
$_POST['f_email']))
    {
      
// If not empty we will execute this code.

      // Here we will convert the password to an md5 encrypted code.
      
$password md5($_POST['f_password']);

      if(!
mysql_query("INSERT INTO users 
      (username,password,firstname,lastname,email) 
      VALUES('"
.$_POST['f_username']."',
      '"
.$password."',
      '"
.$_POST['f_fname']."',
      '"
.$_POST['f_sname']."',
      '"
.$_POST['f_email']."') "))
      {
        echo 
"There was an error tryign to write the information to the database.";
      }
      else
      {
        echo 
$_POST['f_username']." has succesfully been added.";
      }
    }
    else
    {
       
// Not all information has been given.. you will 
       // automaticly return to the register page.
       
header("Location: ".$_SERVER['HTTP_REFERER']." ");
    }
}
elseif(
$_POST['f_login'])
{
   
$get_user mysql_query("SELECT * FROM users WHERE 
   username='"
.$_POST['f_username']."' 
   AND password='"
.md5($_POST['f_password'])."' ");

   if(
mysql_num_rows($get_user) > 0)// Means it's got result.
   
{
       
$_SESSION['s_username'] = $_POST['f_username'];
       
$_SESSION['s_password'] = md5($_POST['f_password']);

       
// The session variables have been made.
       // You can send your user to the wanted page, in this case.. index.php.
       // Please change the domain to your own.
       
header("Location: http://www.domain.com/index.php");
   }
   else
   {
       
$_SESSION['login_error'] = "Your login information was incorrect.";
       
// Please change the domain to your own.
       
header("Location: http://www.domain.com/login.php");
   }
}

?>




If there is an error during the login it should look like this:
foutlogin.jpg


Information

As you can see we use the md5() function of PHP.
The md5() function creates an md5 hash of the string you put in.
This means it will transfer the string into a long unreadable code which is very unlikely to get hacked by just anyone.

You use this function for the security of your data and ofcourse your most valuable users.



You can now log in using the form, browse to it and fill it out.
After logging in you should be redirected to index.php if your login information is right.

We have now got the script that should let us log in succesfully.
But why would someone log in if there are no secured pages... and how do you make those "secure pages"?

We have told you to create a PHP file: index.php.
This will be the page which we are going to secure.

Step 6 - Secured page

Copy and paste the following script into index.php


Code:


<?php
session_start
();// We need the session to keep the user logged in.
include('connect.php'); // We need to connection to execute queries

   
$get_user mysql_query("SELECT * FROM users WHERE 
   username='"
.$_SESSION['s_username']."' 
   AND password='"
.$_SESSION['s_password']."' ");

   if(
mysql_num_rows($get_user) > 0)// Means it's got result.
   
{
       
$row_user mysql_fetch_array($get_user);// provides you with user info
       
echo "
       Welcome "
.$row_user['firstname']." ".$row_users['lastname']."
       <br><br>
       Click <a href='logout.php'>here</a> to log out!"
;

       
// This will output a welcome message plus the link to the logout file.
   
}
   else
   {
       
// The user is not logged in.. so that means he has got to go to the login page.
       // Please change the domain to your own.
       
header("Location: http://www.domain.com/login.php");
   }
?>



All we do above here is check if the user his/her infromation is unique and equals the database records.
If so.. the user is logged in... if not... we will send our user to the login form where he/she can login anyway.

Try to log in using the login form, when it's succesful you will automaticly be redirected to index.php ... the now secured file.
you will be able to view the content of this file now, it should look like this ( also depending on the username ):
logout.jpg


To test if it really works you could close your browser and browse to index.php.
By closing the browser you will destroy your session values, this way your script sees that the person is not logged in and will redirect you to login.php.

All there is left to do now is create the logout.php file to allow the users to logout from your system.

Step 7 - Logout

The logout file is one of the most simple pages you can imagine.
All this file will do is destroy the session variables and send them to the login page.
This way the user won't be able to access index.php anymore.

Copy and paste the following code into logout.php:


Code:


<?php
session_start
();// You need to open the session.. if not it wont get destroyed.

    /*session_destroy() is the function to destroy all current session values
      instead of this you could also use the unset() function.
      With unset you will have to specify what variables you want to be desroyed.
      Example: unset($string,$string2);*/
    
session_destroy();
    
// Please change the domain into your own.
    
header("Location: http://www.domain.com/login.php");

?>




And voilá ... your own simple but secured login system.
Now all you have to do is style and tune it and it's ready to use.

If there are any errors or difficulties, please let me know and i will help you. Thanks for reading this tutorial and I hope you have learned something from it.
« Previous Next »




Comments

Patches.tgz - 2009-05-10
I strongly suggest against using this code, as this code is vulnerable to an SQL injection (if magic quotes are disabled, and since magic quotes are being removed in PHP6, this code will have no protection at all under PHP6).

I'm also a little bit confused as to why you used PHP's function to hash the p***word, when MySql itself provides a function to do so. Like this:


Code:



/*I'll ignore the fact that this is a terribly in-secure method of creating
 * an SQL query */ 

      if(!mysql_query("INSERT INTO users 
      (username,p***word,firstname,lastname,email) 
      VALUES('".$_POST['f_username']."',
      'MD5(".$_POST['f_p***word'].")',
      '".$_POST['f_fname']."',
      '".$_POST['f_sname']."',
      '".$_POST['f_email']."') ")) {
etc...



Side note:
MD5 Sums are not as secure as you make them out to be, they're often susceptible to brute force attacks. In any case they should be salted, but even then, they can possibly compromised via brute force.

Remco - 2009-05-11
That's right patches.tgz ,
It's a simple login system.
It's not protected against SQL injections and i didn't include the salt because it would be too much to put it all in one tutorial.

but that might be a good reason to make a tutorial how to secure your login system ;)

I hope some people did found this tutorial useful though.

Mauez - 2009-06-05
Ive try to load the login.php in my browswer using http://localhost/login/login.php but when I try to login... there's an error when it comes to session.. the error goes like this

''Warning: Cannot send session cookie - headers already sent by (output started at c:apachehtdocsloginlogin.php:2) in c:apachehtdocsloginlogin.php on line ''

please can you help me how can i debug this errors...


your help is hight appreciated...

Remco - 2009-06-18
Hey Mauez,
As far as i know i don't do anything with cookies.
All i do in my script is use sessions.
Could you please post the content of your login.php file here?

If there is nothing wrong with the script it could be your server settings because it looks kinda weird.

Flamer - 2009-07-17
In addition to the comment provided by Patches.tgz:
Placing the MD5 function inside the SQL query limits the encryption posibilitys a bit. Its a common fact that MD5 hashes can be encoded back to the ownes p***word but there are many ways to ensure the security of the givin p***word which i know that Remco has used on his site!

1). Dont use a single encryptment, make it at least double or go for the ultimate overkill by encrypting it for about a 10 times! Make a function for it and voilá ur done.
E.G.


Code:

<?
function encryptP***word($p***){
    
$p***word md5($p***.sha1(md5($p***.sha1($p***))).sha1(md5($p***)));
    return 
$p***word;
}
//End function
?>



Flamer - 2009-07-17
2).Offcourse you MUST combine this with a code/function to clean the giving information for SQL injections!
E.G.


Code:

<?
function clearStringSQL($string){
    
$string stripslashes($string);
    
$string htmlentities($stringENT_QUOTES);
        if(
function_exists('mysql_real_escape_string')){
        
$string mysql_real_escape_string($string);
        }
    return 
$string;
}
//End function
?>


Flamer - 2009-07-17
3). You can use something they call Salt and Pepper! Place a string in front of the users unencrypted p***word and another word, different from the first one, behind the p***word. If the p***word is p***word and the salt is salt and the pepper is pepper then the encrypter p***word would be saltp***wordpepper. The user isnt aware about this and also doesnt need to be because he still would be filling in the p***word he knows. The system only encrpts it. If you use multiple salts and peppers then the hacker, if he succeeds getting the unencrypted p***word, will still need to find his way of getting the REAL p***word.

Combine this all together will bring up something similair to this:

Flamer - 2009-07-17


Code:

<?
// ***    Define the salt and peppers! Just a bunch of bull 
    
$salt1    =    "appels";

    
$pepper1    =    "p***word";
// ***    Get the original non-encrypted p***word from the userform
    
$real_p***word_giving_by_the_user    =    "test;"    # This should be something like: $_POST['the_p***word_field_name'];
// ***    Mix it all up!
    
$p***word_to_import_into_your_database    =    encryptP***word(clearStringSQL($salt1.$real_p***word_giving_by_the_user.$pepper1));
// ***    This should be the place to let PHP insert the information into the database but i want to print it out for ya first.
    
print($p***word_to_import_into_your_database);
?>


Wareitar - 2010-03-08
Someone PLEASE remove this JUNK tutorial....

I've followed your tutorials TO THE POINT atm. And frankly. As mr. Flamer (you could've picked another name mate...) here pointed out, this is just stupidly insecure, sure it's an easy and fast way, and you have a md5 hash, sure... But still insecure and not resistant to injections even.

Secondly, seriously, why would you want a page where you can do nothing unless you login at all... It just fails.
Third, update your flipping tutorial or remove it man. This fails on the newest WAMP server.

And really, ***** this....

Qakbar - 2010-03-12
Hi i'm trying to create a login system of my own, i'm new to php and hav found a script thta i have managed to tweak.
I want to add a field where it will automatically tell me when the user registered below is my MySQL
CREATE TABLE IF NOT EXISTS `members` (
`member_id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(50) DEFAULT NULL,
`lastname` varchar(50) DEFAULT NULL,
`login` varchar(50) NOT NULL,
`p***wd` varchar(32) NOT NULL DEFAULT '',
`email` varchar(75) NOT NULL DEFAULT '',
`date` datetime NULL,
PRIMARY KEY (`member_id`)
) ENGINE=MyISAM;

and here is my insert query in my registration script.

//Create INSERT query
$qry = "INSERT INTO members(firstname, lastname, login, email, date, p***wd) VALUES('$fname','$lname','$login','$email','now()','".md5($_POST['p***word'])."')";
$result = @mysql_query($qry);
Everthing else works fine but it does not add the date to the mysql table only a whole load of zeros.

Any help will be much appreciated,qakbar@hotmail.co.uk.

Thanks

You have to be logged in to write a comment.

.