About O'REILLY cookies example

I’m looking to a “Persistent Login Cookie” example:

Set cookie: http://phpsecurity.org/code/ch07-3

<?php

/*
+------------+------------------+------+-----+---------+-------+
| Field      | Type             | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------+-------+
| username   | varchar(25)      |      | PRI |         |       |
| password   | varchar(32)      | YES  |     | NULL    |       |
| identifier | varchar(32)      | YES  | MUL | NULL    |       |
| token      | varchar(32)      | YES  |     | NULL    |       |
| timeout    | int(10) unsigned | YES  |     | NULL    |       |
+------------+------------------+------+-----+---------+-------+
*/

$salt = 'SHIFLETT';

$identifier = md5($salt . md5($username . $salt));
$token = md5(uniqid(rand(), TRUE));
$timeout = time() + 60 * 60 * 24 * 7;

setcookie('auth', "$identifier:$token", $timeout);

?>

Check cookie: http://phpsecurity.org/code/ch07-4

<?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 */
}

?>

Ok, there are some things I don’t understand. In the checking part, why is the token checked, if the cookie was stolen it will be ok anyways (well in this case I can understand you have to be paranoid), but in the checking of the md5 identifier, if the identifier was found in the database, this “md5($salt . md5($record[‘username’] . $salt)))” will allways match because is the only way the script insert it in the DB. ¿?¿?

Thanks :wink:

It’s simply just an added layer of protection, of course if a cookie was stolen one would assume the token and identifier would match but in some cases the token might match while the identifier doesn’t and vise versa. Simply put it’s just another way to prevent someone with an incorrect correct from been able to attack/spam the website.