Authentication

Build a Secure Password Reset Flow in PHP

Design password reset tokens that are random, single-use, time-limited, and stored as hashes.

Generate a reset token

$token = bin2hex(random_bytes(32));
$tokenHash = hash('sha256', $token);
$expiresAt = (new DateTimeImmutable('+30 minutes'))->format('Y-m-d H:i:s');

Store the hash, user ID, expiry, and used status in a dedicated table. Send the original token only in an HTTPS reset link.

Validate and consume the token

When the user submits the link, hash the supplied token and find an unused, unexpired record using a prepared statement.

Within a transaction:

  1. Lock and verify the reset-token row.
  2. Confirm it has not expired or been used.
  3. Hash the new password with password_hash().
  4. Update the user's password.
  5. Mark the token as used and invalidate other outstanding tokens.
  6. Commit the transaction.

Protect the workflow

Return a generic response whether or not an email exists. Rate-limit requests, avoid logging tokens, and notify the account owner after a successful reset.

Revoke existing sessions after a password reset when appropriate for the application's risk model.