Using Cookies in PHP

4.01 (905)

Practical Cookies : User Logon

To give a more detailed look into how to use cookies, I am going to show you how to create a little login form so that you can store the username and password in a cookie. We will use more complicated cookies now so that you can learn the full use of setcookie().

<html>
<head>
<title>User Logon</title>
</head>
<body>
  <h2>User Login </h2>
  <form name="login" method="post" action="login.php">
   Username: <input type="text" name="username"><br>
   Password: <input type="password" name="password"><br>
   Remember Me: <input type="checkbox" name="rememberme" value="1"><br>
   <input type="submit" name="submit" value="Login!">
  </form>
</body>
</html>


This is the code for our login form, which will produce the following (CSS excluded):



Now that we have our form, we will create our login script. We must decide what restrictions we are going to place on the cookie. I have decided that this will only run on the www.example.com domain and in the /account directory only. Hence,

Login Code
<?php
/* These are our valid username and passwords */
$user 'jonny4';
$pass 'delafoo';

if (isset(
$_POST['username']) && isset($_POST['password')) {
    
    if ((
$_POST['username'] == $user) && ($_POST['password'] == $pass)) {    
        
        if (isset(
$_POST['rememberme'])) {
            
/* Set cookie to last 1 year */
            
setcookie('username'$_POST['username'], time()+60*60*24*365'/account''www.example.com');
            
setcookie('password'md5($_POST['password']), time()+60*60*24*365'/account''www.example.com');
        
        } else {
            
/* Cookie expires when browser closes */
            
setcookie('username'$_POST['username'], false'/account''www.example.com');
            
setcookie('password'md5($_POST['password']), false'/account''www.example.com');
        }
        
header('Location: index.php');
        
    } else {
        echo 
'Username/Password Invalid';
    }
    
} else {
    echo 
'You must supply a username and password.';
}
?>


This code is fairly simple if you break it into parts. First, we have our valid username and password defined so that we can check if the user has entered the correct values. We then check if the user has actually submitted the form and the required values using isset($_POST['username']). If they haven't, a nice error message is displayed.

We then do the important check of if the entered values are equal to the preset username and password. If they aren't we display an error message, however, if they are, the cookie will be set. As you can see we set the cookie using two different methods. If the user has checked the Remember Me box, then the cookie is set to expire at the time of time()+60*60*24*365 which is equal to one years time. The time() function returns the seconds since the start of Unix operating system (1972).

We have used the domain and path parameters of setcookie() to restrict the domain to www.example.com/account as we have specified. If the user has not checked the Remember Me box, then the cookie does not have an expiry time (we have set it to false), hence it will be deleted when the user closes their browser.

You should have also noticed how we have set the password cookie. Instead of just saving the password to a cookie, we have encrypted or hashed it using the md5() function. This function hashes a string so that the original data cannot be recovered. This increases the security of storing the password, but doesn't make it much more difficult for us to deal with.

This script also utilises the header() function to redirect to the index.php page once the cookie has been set. It is important to note that this function can't have any HTML output before calling it, the same as setcookie(). Note: If you are using IIS and not Apache, then you have to use a HTML redirect (META tags) as header() will not work.


Accessing the Data


We currently have a form which submits a username and password, and a login script which sets the cookie on the user's machine. Now we need to access this data, so that it can be used. We are going to access it so that we can validate that the user viewing index.php has actually logged in.

Validating
<?php
/* These are our valid username and passwords */
$user 'jonny4';
$pass 'delafoo';

if (isset(
$_COOKIE[['username']) && isset($_COOKIE['password')) {
    
    if ((
$_POST['username'] != $user) || ($_POST['password'] != md5($pass))) {    
        
header('Location: login.html');
    } else {
        echo 
'Welcome back ' $_COOKIE['username'];
    }
    
} else {
    
header('Location: login.html');
}
?>


In this script, we just check that the cookie exists and is valid. If they aren't, then the user is redirected back to the login form. Otherwise a welcome message is included. The only important thing to notice is how we have validated the password. Before on the login.php script, we have encrypted our password using md5() and as this encryption cannot be undone, we must compare encrypted versions. Hence, we encrypt our preset value and compare it to the already hashed cookie value. This way, there is no chance of the original password becoming available.
Rate this article: BAD 1 2 3 4 5   GOOD
<<     Page 2 of 3    >>

Build Your Own Database Driven Website Using PHP & MySQL

  • Installation instructions for Windows, Linux and Mac OS X
  • Instantly apply working code examples from the book to your Website
  • Build a working Content Management System from scratch
  • Master MySQL database administration
  • Fully updated for PHP 5

       Download FREESample Chapters Now!

Ads

PHPNerds Newsletter