PHP - How to implement password reset and token expiry

I'm looking to set up a php password recovery script, using a token which expires after 24 hours. But I'm not sure how to go about it. I have SHA1 encrypted user passwords at the moment. All I want to do I think is append a token to the URL which is sent to the user when they request a password reset. But how do I go about doing this properly and what do I need to store in the database?


Solution 1:

  1. When your user requests a password reset, generate a token and calculate its expiry date
  2. Store the token and its expiry date in separate columns in your users table for that user
  3. Send an email to the user containing the reset link, with the token appended to its URL
  4. When your user follows the link, grab the token from your URL (perhaps with $_GET['token'])
  5. Verify the token against your users table
  6. Check that it's not past its expiry date yet
    • If it has expired, invalidate it, perhaps by clearing the fields, and allow the user to resend
  7. If the token is valid and usable, present your password reset form to the user
  8. Validate and update the password and clear the token and expiry fields

Solution 2:

I would not use a database at all. But one way encryption instead.
Just send necessary information in the hyperlink supplied in the mail, signed by the hash. Something like this

$token = sha1($user_id.$time.$user_pass.$salt).dechex(time()).dechex($user_id);
$link = "http://".$domain."/restorepass/?token=$token";

By receiving it just split and decode it back, and then check hash and timeout.

Solution 3:

You need to store a unique token and a token expiry timestamp. When users visits the unique URL you must validate the token, the username and the token expiry timestamp. If everything fine you can send a new password or display a form where user can setup a new password.