14.4. Storing Passwords

Problem

You need to keep track of users’ passwords so they can log in to your web site.

Solution

When a user signs up, encrypt her chosen password with crypt( ) and store the encrypted password in your database of users:

// encrypt the password
$encrypted_password = crypt($_REQUEST['password']);

// store $encrypted_password in the user database 
$dbh->query('INSERT INTO users (username,password) VALUES (?,?)',
            array($_REQUEST['username'],$encrypted_password));

Then, when that user attempts to log in to your web site, encrypt the password she supplies with crypt( ) and compare it to the stored encrypted password. If the two encrypted values match, she has supplied the correct password:

$encrypted_password = 
    $dbh->getOne('SELECT password FROM users WHERE username = ?',
                 array($_REQUEST['username']));

if (crypt($_REQUEST['password'],$encrypted_password) == $encrypted_password) {
  // successful login
} else {
  // unsuccessful login
}

Discussion

Storing encrypted passwords prevents users’ accounts from becoming compromised if an unauthorized person gets a peek at your username and password database. (Although such unauthorized peeks may foreshadow other security problems.)

When the password is initially encrypted, crypt( ) supplies two randomly generated characters of salt that get prepended to the encrypted password. Passing $encrypted_password to crypt( ) when testing a user-supplied password tells crypt( ) to use the same salt characters again. The salt reduces ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.