Create Login Admin & Logout Page in PHP w/ SESSION n MySQL

[box type=”warning”]This post has been outdated. Please check the new one here where we have discussed how to create the system using session and cookie with remember me option.[/box]
secured login In this tutorial we shall see, how to create a basic Login System in PHP using SESSION. We shall discuss, a fully secured login system with MySQL connectivity along with an Online Demo. The login system will redirect access to the admin file if not logged in! It will also show the current user name where ever you want [In the Demo page it is on the Page heading]

For those who are a little familiar with PHP, here is the download source code and Online Demo link

[box type=”warning”]This post has been outdated. Please check the new one here where we have discussed how to create the system using session and cookie with remember me option.[/box]

Account Login Details for the Demo page are:

  • User Name: swashata; Password: swashata;OR
  • User Name: admin; Password: admin

If you want to understand the coding behind the login system, then read on below…

#0: Strategy Used behind the Login System:

Here we shall use 5 files for making the whole system.file structure

  • config.php: The main file for holding the information related to the admin MySQL table. We shall discuss in brief how to create the table. For information do check the MySQL posts.
  • admin.php: For administrative functions. It will redirect to login.php if not authorized already;
  • login.php: A webpage for displaying form of login. It will submit the form to check_login.php where it will be processed further;
  • check_login.php: A PHP script to check the login details from the MySQL Table. If successfully matched, then it will register the Session, else will redirect back to the login.php file with error message;
  • logout.php: It will delete the session, and will redirect back to login.php file with success message;

#1: Setting up the MySQL Table:

We shall use a MySQL table like this for storing administrator information:

id user_name user_pass
1 admin admin
2 swashata swashata

Basically we shall encrypt the password inside the table. Just for the demonstration I have showed the passwords above…

Now create a Database and inside it create a table login_admin with the following MySQL query command:

CREATE TABLE login_admin
(
id INT NOT NULL AUTO_INCREMENT,
user_name VARCHAR(100),
user_pass VARCHAR(200),
PRIMARY KEY (id)
)

Now insert the two user information inside the table with the following command:

INSERT INTO login_admin (user_name, user_pass)
VALUES
(
‘swashata’, SHA(‘swashata’)
)

INSERT INTO login_admin (user_name, user_pass)
VALUES
(
‘admin’, SHA(‘admin’)
)

Now your MySQL table is ready for use!

#2: Setting up the config.php file:

As mentioned before, it just contains all the necessary MySQL Database connection information. Here is the code for this file:

<?php
/**********************************************************************
 *Contains all the basic Configuration
 *dbHost = Host of your MySQL DataBase Server... Usually it is localhost
 *dbUser = Username of your DataBase
 *dbPass = Password of your DataBase
 *dbName = Name of your DataBase
 **********************************************************************/
$dbHost = 'localhost';
$dbUser = 'Data Base User Name';
$dbPass = 'Data Base Password';
$dbName = 'Data Base Name';
$dbC = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName)
        or die('Error Connecting to MySQL DataBase');
?>

Just save this file with the above codes.

#3: Code behind the login.php File:

It shows up the login form and moves it to check_login for further processing!

<!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>
    <title>Login Demo</title>
</head>
<body>
<?php
    $login_form = <<<EOD
<form name="login" id="login" method="POST" action="check_login.php">
<p><label for="username">Please Enter Username: </label><input type="text" size="100" name="username" id="username" value="Enter Username here" /></p>
<p><label for="password">Please Enter Password: </label><input type="password" size="40" name="password" id="password" value="abracadabra" /></p>
<p><input type="submit" name="submit" id="submit" value="Submit"/> <input type="reset" name="reset" id="reset" value="reset"/></p>
</form>
EOD;
$msg = $_GET['msg'];  //GET the message
if($msg!='') echo '<p>'.$msg.'</p>'; //If message is set echo it
echo "<h1>Please enter your Login Information</h1>";
echo $login_form;
?>
</body>
</html>

The $msg variable is used to show any message to the user using GET method.

#4: Code Behind the check_login.php file:

<?php
define(DOC_ROOT,dirname(__FILE__)); // To properly get the config.php file
$username = $_POST['username']; //Set UserName
$password = $_POST['password']; //Set Password
$msg ='';
if(isset($username, $password)) {
    ob_start();
    include(DOC_ROOT.'/config.php'); //Initiate the MySQL connection
    // To protect MySQL injection (more detail about MySQL injection)
    $myusername = stripslashes($username);
    $mypassword = stripslashes($password);
    $myusername = mysqli_real_escape_string($dbC, $myusername);
    $mypassword = mysqli_real_escape_string($dbC, $mypassword);
    $sql="SELECT * FROM login_admin WHERE user_name='$myusername' and user_pass=SHA('$mypassword')";
    $result=mysqli_query($dbC, $sql);
    // Mysql_num_row is counting table row
    $count=mysqli_num_rows($result);
    // If result matched $myusername and $mypassword, table row must be 1 row
    if($count==1){
        // Register $myusername, $mypassword and redirect to file "admin.php"
        session_register("admin");
        session_register("password");
        $_SESSION['name']= $myusername;
        header("location:admin.php");
    }
    else {
        $msg = "Wrong Username or Password. Please retry";
        header("location:login.php?msg=$msg");
    }
    ob_end_flush();
}
else {
    header("location:login.php?msg=Please enter some username and password");
}
?>

As you can see it registers $_SESSION[‘name’] superglobal variable along with session_register and then redirects to admin.php. Now lets see what the admin.php file has to protect it from unauthorized use! Also note that if username and password do not match, then it redirects back to the login.php file with an error $msg.

#5: Code behind admin.php file:

<?php
session_start(); //Start the session
define(ADMIN,$_SESSION['name']); //Get the user name from the previously registered super global variable
if(!session_is_registered("admin")){ //If session not registered
header("location:login.php"); // Redirect to login.php page
}
else //Continue to current page
header( 'Content-Type: text/html; charset=utf-8' );
?>
<!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>
    <title>Welcome To Admin Page Demonstration</title>
</head>
<body>
    <h1>Welcome To Admin Page <?php echo ADMIN /*Echo the username */ ?></h1>
    <p><a href="logout.php">Logout</a></p> <!-- A link for the logout page -->
    <p>Put Admin Contents</p>
</body>
</html>

I have put comments every where! So you will be able to easily understand the code! Basically, here you need to be creative to put the admin contents properly! What ever it is, it will only be shown to authorized users. Also we have set a constant ADMIN to fetch the username from the super global variable $_SESSION[‘name’] and we can echo it where ever we want!

#6: Logging out with logout.php

It is used to destroy the current session. It is very simple!

<?php
session_start(); //Start the current session
session_destroy(); //Destroy it! So we are logged out now
header("location:login.php?msg=Successfully Logged out"); // Move back to login.php with a logout message
?>

Save the file with the above code and you are done!

[box type=”warning”]This post has been outdated. Please check the new one here where we have discussed how to create the system using session and cookie with remember me option.[/box]


So, now you have successfully made a PHP login system using SESSION. Later we shall see how to use cookie and HTTP authentication to make personal login systems! I hope you have enjoyed this tutorial. Do give your feedback! If you face any problem, feel free to ask!

112 comments

  1. Pingback: Get Parent directory of Current URL using PHP dirname function | InTechgrity

  2. Mafia Kennels

    Hi creating log in and log out admin page is the very important parts of any blog all is very nice collection thanks for it.

  3. khairul66

    Hi, can i ask what is $login_form = <<<EOD that you put in the login.php file?
    can you explain?

    • Swashata Post author

      EOD is just a Heredoc string in PHP. Whatever written in between

      $your_var = <<<EOD
      And anything can go here. Including $other_variable.
      EOD;
      

      Will keep its quote structure intact and also you can insert variables inside. For more info have a look at this -> http://php.net/manual/en/language.types.string.php Scroll down to Example #2 Heredoc string quoting example

      Also note that, you should not give any indentation to the closing EOD. So this is wrong

      if(isset($something)) {
          $may_var = <<<EOD
          bla bla
          EOD;
      }
      echo $may_var;
      

      Is wrong. Instead this one is correct:

      if(isset($something)) {
          $may_var = <<<EOD
          bla bla
      EOD;
      }
      echo $may_var;
      

      In the tutorial you can also end the PHP tag instead of echoing it. So, it would be then:

      <!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>
          <title>Login Demo</title>
      </head>
      <body>
      <?php
      $msg = $_GET['msg'];  //GET the message
      if($msg!='') echo '<p>'.$msg.'</p>'; //If message is set echo it
      ?>
      <h1>Please enter your Login Information</h1>
      <form name="login" id="login" method="POST" action="check_login.php">
      <p><label for="username">Please Enter Username: </label><input type="text" size="100" name="username" id="username" value="Enter Username here" /></p>
      <p><label for="password">Please Enter Password: </label><input type="password" size="40" name="password" id="password" value="abracadabra" /></p>
      <p><input type="submit" name="submit" id="submit" value="Submit"/> <input type="reset" name="reset" id="reset" value="reset"/></p>
      </form>
      </body>
      </html>
      

      I showed the EOD way, because some people like you may get interest in it and will try to learn it! 🙂

      • chandra mohan dhakar

        Hi i got good knowlege …and i make it to more practice or develope a page for big coding .
        i am just asking that ” is it possible for more than 1000 lines of code ? ” .

        • lights

          sir ano gamit nyong database?xampp b yn?my error kc ung akin e.salamat

  4. Raj

    hi,i used ur code but in check_login.php page i am getting errors like

    PHP Notice: Undefined variable: dbC in /home/ramesh/Public/magazine/admin/check_login.php on line 14

    ,PHP Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in /home/ramesh/Public/magazine/admin/check_login.php on line 14
    ,
    PHP Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in /home/ramesh/Public/magazine/admin/check_login.php on line 15

    ,
    PHP Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in /home/ramesh/Public/magazine/admin/check_login.php on line 18

    Can u please find the problem and clarify my problems…plz

    • Swashata Post author

      [Edited] Sorry, it seems there is a database error. Make sure the database and the table exists

      • hbg_648

        hi sir swashata..thank u very much for your posts..i got a little information from your post.but since i directly enrolled in 3rd year 2nd semester,that’s why i didn’t know PHP CODE..can u help me how to make log in form for admin and user? it’s my pleasure to read your post.it’s really useful to me as a student.thank u…

  5. sharmaine

    hi, just want to know what u mean by “SHA” in inserting values to the table. Where to insert values? could it possible to create in the phpMyadmin? thanks!

    • Anandh

      SHA – Its just an encryption algorithm to protect your password.
      you can create and insert table data without SHA algorithm.
      You can use phpmyadmin too, for doing all these!

  6. Bernard

    I’ve sm question…
    why I always failed to logging in…no errors found but just cant enter my admin page…
    I create db on my site…already make 1 username…but failed…

    can u tell me why ? or i missed smthing ?
    my life depend on this…-.-
    pls help…

    btw,,sory w/ the english…not good either,,,

    • Swashata Post author

      This post is outdated. I will update it with a better code once I get time. Probably this is happening because we now dont use session_is_registered. use isset($_SESSION[‘name’]).

      • Thacien

        thanks for the good jod did you done for us but me, am begin in programming and i want to become a good programmer but my knowledge is verry small because of our source so i want to ask you please can you help me how can i create an interface of administrator i’m seing source code of login where i use USERNAME and PASSWORD after i press button login or logout
        please help me it is not a comment!!!

  7. Allif

    Hi,

    this is a very good info on admin login that just what i was looking for. will try to use it and let you know if it works with me.

    thank you

  8. Steve

    Swashata, How to include a new files into the system ? For example

    I want to add

    j22.php
    Into admin folder and don’t view j22.php before login so the question is what’s the check login code that I could add it to any php file ?

  9. Alyssa Janine

    hi, i have some problem, i don’t know what is the right codes in making a log in page of User and Admin, using php. would yo pls help me with the right code? also with homepage. Thanks!

  10. Alyssa Janine

    hi, i would like to ask what is the right codes for log in page of user and admin using php. and html. please help me. I need it before feb 8, 2011.Thanks

  11. Damian

    I have the same problem : Fatal error: Call to undefined function mysqli_connect() in /home/sleeping/public_html/config.php on line 13

    The database exists and everthing.
    When you create users, its SHA1 not SHA.

    Any idea?

    • Nischal

      Fatal error: Call to undefined function mysqli_connect() in /home/cricnepa/public_html/profile/pro/config.php on line 7

  12. mayuri

    After i create the username and password i get this error.kindly tel me why this happend?

    Notice: Use of undefined constant DOC_ROOT – assumed ‘DOC_ROOT’ in C:\Program Files\EasyPHP5.2.10\www\LMS\check_login.php on line 2

    Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘Data Base admin’@’localhost’ (using password: YES) in C:\Program Files\EasyPHP5.2.10\www\LMS\config.php on line 15
    Error Connecting to MySQL DataBase

  13. khairul66

    Sir, do you know how to encrypt a file in php using AES algorithm. If yes, can you show me the coding..

  14. saikiran

    hey plez tell me that how to embed this code into my data base

  15. mark

    SQL query:

    INSERT INTO login_admin( user_name, user_pass )
    VALUES (

    ‘swashata’, SHA( ‘swashata’ )
    )
    INSERT INTO login_admin( user_name, user_pass )
    VALUES (
    ‘admin’, SHA( ‘admin’ )
    )
    MySQL said:

    #1064 – You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘INSERT INTO login_admin (user_name, user_pass)
    VALUES
    (
    ‘admin’, SHA(‘a’ at line 7

    • mfelke1982

      If your using phpmyadmin, click on insert and on the functions tab you’ll see one called “SHA1”. That’s how I got it to work.

  16. neha

    Parse error: syntax error, unexpected ‘<' in C:\wamp\www\loginphp1\login.php on line 9

    this is the error i am getting in login.php page when i removed EOD tag. Before removing this tag it was giving me an error of parsing :
    Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in C:\wamp\www\loginphp1\login.php on line 14

  17. mfelke1982

    Would I have to use the isset function in order to replace session_register and session_is_registered functions from giving me errors?

  18. mfelke1982

    Good News! I got it to work!!!

    Here’s how I got it….

    On check_login.php:

    and on admin.php…

    Welcome To Admin Page Demonstration

    Welcome To Admin Page
    Logout
    Put Admin Contents

    Hope this help you out for replacing the seesion_is_registered functions.

  19. mfelke1982

    Sorry, but my fixed code got stripped out is there a away I can post it?

  20. Sagive

    Any Update about it NOT login in problem.. what part should i replace with what?

  21. coolphp

    Hello friend,
    I know a little bit of mysql and php.i want to create a site were peoples can login and upload their pictures to store it and when they want to see or download they can login and download.I have created the database ,login and all other details but i am not able to do post login steps.I am stuck here.The site works with out login(guest) and saves/download the image in database but i dont know how to save a users images in a particular login.

  22. Nitesh

    HI iam facing downloading problem i can’t download or see the demo.

  23. Nitesh

    HI iam facing downloading problem i can’t download or see the demo

  24. Helen Neely

    Thanks for this complete login/admin application. I was looking for something to get my simple app working and this came in very handy.

    BTW – The demo page you have up there is not available, any chance of taking a look?

    Great stuff.

  25. megh

    whenever i logout using session_destroy();
    my session is notb destroyed and clicking back on the back button of my browser directs to the home page again.what can be the reason for that

Comments are closed.