14.6. Dealing with Lost Passwords
Problem
You want to issue a password to a user who claims he’s lost his password.
Solution
Generate a new password and send it to the user’s email address (which you should have on file):
// generate new password $new_password = ''; $i = 8; while ($i--) { $new_password .= chr(mt_rand(33,126)); } // encrypt new password $encrypted_password = crypt($new_password); // save new encrypted password to the database $dbh->query('UPDATE users SET password = ? WHERE username = ?', array($encrypted_password,$username)); // email new plaintext password to user mail($email,"New Password","Your new password is $new_password");
Discussion
If a user forgets his password, and you store encrypted passwords as
recommended in Recipe 14.5, you
can’t provide the forgotten password. The one-way
nature of crypt( )
prevents you from retrieving
the unencrypted password.
Instead, generate a new password and send that to his preexisting contact address. If you send the new password to an address you don’t already have on file for that user, you don’t have a way to verify that the new address really belongs to the user. It may be an attacker attempting to impersonate the real user.
Because the email containing the new password isn’t encrypted, the code in the Solution doesn’t include the username in the email message to reduce the chances that an attacker that eavesdrops on the email message can steal the password. To avoid disclosing a new password by email at all, let a user ...
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.