Essential PHP Security Book Cover
Essential PHP Security by Chris Shiflett
About | Contents | Buy Now | Reviews | Errata | Code
  1. Foreword
  2. Preface
  1. Introduction
  2. Forms and URLs
          ch02.pdf
  3. Databases and SQL
  4. Sessions and Cookies
          ch04.pdf
  5. Includes
  6. Files and Commands
  7. Authentication and Authorization
  8. Shared Hosting
  1. Configuration Directives
  2. Functions
  3. Cryptography
  4. Index

Check a Persistent Login Cookie

(Chapter 7, Authentication and Authorization - Pg 71-73)

< Back to Code Repository

<?php

/* mysql_connect() */
/* mysql_select_db() */

$clean = array();
$mysql = array();

$now = time();
$salt = 'SHIFLETT';

list(
$identifier, $token) = explode(':', $_COOKIE['auth']);

if (
ctype_alnum($identifier) && ctype_alnum($token))
{
    
$clean['identifier'] = $identifier;
    
$clean['token'] = $token;
}
else
{
    
/* ... */
}

$mysql['identifier'] = mysql_real_escape_string($clean['identifier']);

$sql = "SELECT username, token, timeout
        FROM   users
        WHERE  identifier = '
{$mysql['identifier']}'";

if (
$result = mysql_query($sql))
{
    if (
mysql_num_rows($result))
    {
        
$record = mysql_fetch_assoc($result);

        if (
$clean['token'] != $record['token'])
        {
            
/* Failed Login (wrong token) */
        
}
        elseif (
$now > $record['timeout'])
        {
            
/* Failed Login (timeout) */
        
}
        elseif (
$clean['identifier'] !=
                
md5($salt . md5($record['username'] . $salt)))
        {
            
/* Failed Login (invalid identifier) */
        
}
        else
        {
            
/* Successful Login */
        
}
    }
    else
    {
        
/* Failed Login (invalid identifier) */
    
}
}
else
{
    
/* Error */
}

?>