Secure Login Using Cookies
http://www.phpnoise.com/tutorials/26/1

Introduction
Web security is a common requirement for most sites, for both personal and business use. Understanding how to protect secure areas of your site is an important concept for web developers to understand.
This introductory tutorial is a guide to using the PHP language and PHP cookies to create a simple login procedure. This tutorial should provide you with the means to secure your site.
This tutorial assumes several things about the reader:

  • You are familiar with PHP
     
  • You are familiar with PHP cookies
     
  • You have access to a server or servers running the PHP package

    I will be using the syntax for PHP cookies as provided in the PHP manual, not as used in my previous cookies tutorial found in PHPNoise.

    Creating the Form
    We will be creating all components of the login form on a single page called index.php. We will be building the index.php file to evaluate the various events expected from the login sequence, and respond to them accordingly.
    The first step is creating a login form. This form will be presented to the user when they visit the login page:









     
    <form action=index.php method=post>
    <table align=center style="font-family:arial; font-size:12; border:1 solid #000000;">
      <tr><td colspan=2 align=center bgcolor=#123dd4>LOGIN</td></tr>
      <tr><td align=right>Username: </td><td><input type=text name=user size=15></td></tr>
      <tr><td align=right>Password: </td><td><input type=password name=pass size=15></td></tr>
      <tr><td align=center colspan=2><input type=submit value=Login></td></tr>
    </table>
    </form>

    This form will allow us to submit the form variables (username and password) back to the index.php page for validation. We will need to intercept this submission and evaluate the contents for the existence of valid credentials.

    Evaluating Form Results
    We want to evaluate any form results produced from the users login attempt.
    To do this, we will capture and evaluate the form variables that are expected during a login attempt. If the form variables exist and are properly named, we want to evaluate them to determine if they are valid credentials.
    With only a single user account to verify, we will assume the following variables exist, and have been extracted from a MySQL database, flat file, include file or similar medium:
     





     
    <?php
    $username
    = 'admin';
    $password = 'admin_pass';
    $time=time();
    ?>

    Using these values as valid credentials, we will compare them to the values received from the form login.










     
    <?php
    if ($_POST[user] && $_POST[pass]) {
    if (
    $_POST[user]==$username && $_POST[pass]==$password) {    
      
    setcookie ("user", md5($_POST[user]), $time+3200);
      
    setcookie ("pass", md5($_POST[pass]), $time+3200);
      
    header("Location: index.php");
    } else {
    $login_error= true; }
    }
    ?>

    This piece of code will verify that the user input matches the valid credentials. If there is a valid match, a cookie is created holding the encrypted login information, if there is no match, a flag is set to indicate a login error.
    If you have a MySQL table with users login information, you could use this method to search through the various accounts for the users login credentials, assuming the users username and/or password is a unique value:

    01 
    02 
    03 
    04 
    05 
    06 
    07 
    08 
    09 
    10 
     
    <?php
    if ($_POST[user] && $_POST[pass]) {
    $user_data = mysql_fetch_array(mysql_query("select id, username, password from users where username='$_POST[user]' and password='$_POST[pass]'"));
    if (
    $user_data[id] > 0) {
      
    setcookie ("user", md5($user_data[username]));
      
    setcookie ("pass", md5($user_data[password]));
      
    header("Location: index.php");
    } else {
    $login_error= true; }
    }
    ?>

    Handling Login Results
    After we evaluate the values provided in the login attempt, we need to handle the results of the evaluation gracefully, regardless of a successful or failed login attempt.

    01 
    02 
    03 
    04 
    05 
    06 
    07 
    08 
    09 
    10 
    11 
    12 
    13 
    14 
    15 
    16 
    17 
    18 
     
    <?php
    if ($login_error == true) { ?>
    <table align=center style="font-family:arial; font-size:12; border:1 solid #000000;">
      <tr><td align=center bgcolor=#123dd4>LOGIN ERROR</td></tr>
      <tr><td align=center><b>Invalid Username and/or Password</b><br><br><a href=index.php>Back</a></td></tr>
    </table>
    <?
    } elseif ($_COOKIE[user] == md5($username) && $_COOKIE[pass] == md5($password)) { ?>
    <table align=center style="font-family:arial; font-size:12; border:1 solid #000000;">
      <tr><td align=center bgcolor=#123dd4>SECURE AREA</td></tr>
      <tr><td>You have successfully logged in.<br><br>
       Encrypted Username: <b><?= $_COOKIE[user] ?></b><br>
       Encrypted Password: <b><?= $_COOKIE[pass] ?></b><br>
      </td></tr>
    </table>
    <?
    }
    ?>

    This code snippet provides us with a means of determining if the login attempt was a success or failure. On a successful login attempt, we will issue the encrypted login information to the screen. If the attempt results in failure, we will indicate to the user that they have provided invalid login credentials and provide a button to go back and try again.

    Logging Out
    Allowing the user to logout once they have gained access to the secure area is as simple as expiring the users cookie:








     
    <?php
    if ($logout) {    
    setcookie ("user", md5($_POST[user]), $time-3200);
    setcookie ("pass", md5($_POST[pass]), $time-3200);
    header("Location: index.php");
    }
    ?>

    This snippet will provide the user with a means of expiring the cookies created on login. We then reload the page to allow the browser to refresh the session with the absence of the cookie variables.

    The Complete Script
    Lets tie everything into a single script (index.php) and see what our results are.

    01 
    02 
    03 
    04 
    05 
    06 
    07 
    08 
    09 
    10 
    11 
    12 
    13 
    14 
    15 
    16 
    17 
    18 
    19 
    20 
    21 
    22 
    23 
    24 
    25 
    26 
    27 
    28 
    29 
    30 
    31 
    32 
    33 
    34 
    35 
    36 
    37 
    38 
    39 
    40 
    41 
    42 
    43 
    44 
    45 
    46 
    47 
    48 
    49 
    50 
    51 
    52 
    53 
     
    <?php
    // valid login credentials
    $username = 'admin';
    $password = 'admin_pass';
    // grab current time
    $time=time();

    // handle the logout event
    if ($logout == true) {    
    setcookie ("user", md5($_POST[user]), $time-3200);
    setcookie ("pass", md5($_POST[pass]), $time-3200);
    header("Location: index.php");
    }

    // handle validation event
    if ($_POST[user] && $_POST[pass]) {    
    if (
    $_POST[user]==$username && $_POST[pass]==$password) {
      
    setcookie ("user", md5($_POST[user]), $time+3200);
      
    setcookie ("pass", md5($_POST[pass]), $time+3200);
      
    header("Location: index.php");
    } else {
    $login_error= true; }
    }

    // handle login event, both successful and erroneous, or show login screen
    if ($login_error == true) { ?>
    <table align=center style="font-family:arial; font-size:12; border:1 solid #000000;">
      <tr><td align=center bgcolor=#123dd4>LOGIN ERROR</td></tr>
      <tr><td align=center><b>Invalid Username and/or Password</b><br><br><a href=index.php>Back</a></td></tr>
    </table>
    <?
    } elseif ($_COOKIE[user] == md5($username) && $_COOKIE[pass] == md5($password)) { ?>
    <table align=center style="font-family:arial; font-size:12; border:1 solid #000000;">
      <tr><td align=center bgcolor=#123dd4>SECURE AREA</td></tr>
      <tr><td align=right><a href=index.php?logout=true>Logout</a></td></tr>
      <tr><td>You have successfully logged in.<br><br>
       Encrypted Username: <b><?=  $_COOKIE[user] ?></b><br>
       Encrypted Password: <b><?= $_COOKIE[pass] ?></b><br>
      </td></tr>
    </table>
    <?
    } else {
    ?>
    <form action=index.php method=post>
    <table align=center style="font-family:arial; font-size:12; border:1 solid #000000;">
      <tr><td colspan=2 align=center bgcolor=#123dd4>LOGIN</td></tr>
      <tr><td align=right>Username: </td><td><input type=text name=user size=15></td></tr>
      <tr><td align=right>Password: </td><td><input type=password name=pass size=15></td></tr>
      <tr><td align=center colspan=2><input type=submit value=Login></td></tr>
    </table>
    </form>
    <?
    }
    ?>


    Save this code as index.php and execute it on your server to see the results.

    Conclusion
    Using the methods shown in this tutorial will provide you with a simple method of securing your web site.
    There are other methods of site security available besides cookies: PHP sessions, .htaccess and more. Like cookies, each method has many possible alternatives you can use to secure your site.
    I believe using cookies, with the method shown above, is one of the most portable and easily customized site security methods available.