Hash and verify passwords in PHP
Store passwords with password_hash and check them with password_verify, including rehash on login.
- PHP
- GreenSnippets
- MIT
- Executed with PHP 8.2
<?php
function hashPassword(string $password): string
{
return password_hash($password, PASSWORD_DEFAULT);
}
/** Returns [bool $valid, ?string $newHash] - persist $newHash if it is not null. */
function verifyPassword(string $password, string $storedHash): array
{
if (!password_verify($password, $storedHash)) {
return [false, null];
}
$newHash = password_needs_rehash($storedHash, PASSWORD_DEFAULT)
? password_hash($password, PASSWORD_DEFAULT)
: null;
return [true, $newHash];
}How it works
Never store plain or fast-hashed (MD5, SHA-1, SHA-256) passwords. password_hash with PASSWORD_DEFAULT uses a strong, salted, adaptive algorithm (currently bcrypt) and embeds the salt and cost in the result, so you store only that one string.
On each successful login call password_needs_rehash; if PHP's default has gotten stronger, store the new hash. Note that bcrypt only uses the first 72 bytes of input.
Related snippets
- PHP Tested
Validate emails and URLs in PHP
Use filter_var to validate email addresses and http(s) URLs, with an allow-list for schemes.
- Python Tested
Sign API requests with HMAC-SHA256
Create and verify a timestamped signature over the method, path and body so requests cannot be forged or replayed.
- JavaScript Tested
Generate secure random IDs and integers
Create UUIDs, random integers in a range and URL-safe tokens with the Web Crypto API instead of Math.random.
- PHP Tested
Generate a secure random token in PHP
Create unpredictable tokens for password resets, API keys and CSRF protection with random_bytes.

