A safe password reset flow in PHP

Intermediate  Nov 3, 2026

Send a one-time link that expires, and store only a hash of the token.

A safe password reset flow in PHP
The steps of this tutorial at a glance.
The steps of this tutorial at a glance.

Rules

  • The token must be random and unguessable.
  • Store a hash of the token, not the token itself.
  • It expires quickly (for example 30 minutes) and works once.
  • The "forgot" page gives the same answer whether or not the email exists.
The main points of this section.
The main points of this section.

Table

CREATE TABLE password_resets (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  token_hash CHAR(64) NOT NULL,
  expires_at DATETIME NOT NULL,
  used TINYINT(1) NOT NULL DEFAULT 0,
  UNIQUE KEY (token_hash)
);
The table described by the SQL above.
The table described by the SQL above.
How the code in this section fits into the page.
How the code in this section fits into the page.

Create the token

<?php
$token = bin2hex(random_bytes(32));
$hash  = hash('sha256', $token);

$stmt = $pdo->prepare('INSERT INTO password_resets (user_id, token_hash, expires_at) VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 30 MINUTE))');
$stmt->execute([$userId, $hash]);

$link = 'https://example.com/reset.php?token=' . $token;   // email this
How the code in this section fits into the page.
How the code in this section fits into the page.

Check the token

$hash = hash('sha256', (string)($_GET['token'] ?? ''));
$stmt = $pdo->prepare('SELECT user_id FROM password_resets WHERE token_hash = ? AND used = 0 AND expires_at > NOW()');
$stmt->execute([$hash]);
$row = $stmt->fetch();
Check the token
Check the token

After the new password is set

Hash it with password_hash(), mark the token as used, and end all other sessions of that user.

After the new password is set
After the new password is set

More tutorials