Issue unpredictable, single-use reset tokens and store only a hash with a short expiry. The examples separate the essential operation from the conditions a production implementation must enforce.
What It Does
Issue unpredictable, single-use reset tokens and store only a hash with a short expiry.
Prerequisites
Use a dedicated development environment with test accounts and records. Separate authorization, validation and error handling from response formatting; never copy demonstration-only secrets into production.
Example 1: Core Behavior
The first example isolates the core operation so its result is easy to understand.
<?php
$token = bin2hex(random_bytes(32));
$tokenHash = hash('sha256', $token);
$expiresAt = time() + 900;
echo strlen($tokenHash) === 64 ? 'Persist hash and expiry' : 'Invalid';
Example 2: Alternative or Failure Case
The second example demonstrates an alternative outcome, rule or failure condition.
<?php
$sentToken = 'example-expired-token';
$storedHash = hash('sha256', 'genuine-token');
$expiresAt = time() - 1;
$valid = time() < $expiresAt && hash_equals($storedHash, hash('sha256', $sentToken));
var_export($valid);
Practical Example: Applying the Rule
The practical example shows how to carry the same constraint into application code.
<?php
$token = bin2hex(random_bytes(32));
$digest = hash('sha256', $token);
// In a real workflow delete the token and update the password in one database transaction.
echo hash_equals($digest, hash('sha256', $token)) ? 'Valid once' : 'Invalid';
Important Behavior and Edge Cases
Always invalidate reset tokens in a transaction after successful password change, and do not reveal whether an account exists.
Comparison with Related Functions or Patterns
| Approach | When it differs |
|---|---|
| Securing Password Reset Tokens | Issue unpredictable, single-use reset tokens and store only a hash with a short expiry. |
| Related API or pattern | Email verification links prove inbox access but do not themselves authorize a password reset. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Saving reset tokens in plaintext or allowing an expired token to be reused | Always invalidate reset tokens in a transaction after successful password change, and do not reveal whether an account exists. |
| Substituting a related API without checking its semantics | Email verification links prove inbox access but do not themselves authorize a password reset. |
Key Takeaways
- Issue unpredictable, single-use reset tokens and store only a hash with a short expiry.
- Always invalidate reset tokens in a transaction after successful password change, and do not reveal whether an account exists.
- Email verification links prove inbox access but do not themselves authorize a password reset.
Select this API or pattern based on its documented behavior and the trust boundaries in your own application, and test all external integrations against their actual deployments.