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:
- Lock and verify the reset-token row.
- Confirm it has not expired or been used.
- Hash the new password with
password_hash(). - Update the user's password.
- Mark the token as used and invalidate other outstanding tokens.
- 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.