PHP password_hash() and password_verify() Functions
PHP provides password-specific functions designed to store and verify passwords safely. Do not store plaintext passwords or create a custom password hashing algorithm.
Create a Password Hash
$password = "user supplied password";
$hash = password_hash($password, PASSWORD_DEFAULT);
Store the returned hash in a database column with sufficient room for future algorithm changes. VARCHAR(255) is a common choice.
Verify a Submitted Password
if (password_verify($submittedPassword, $storedHash)) {
// Credentials match.
} else {
// Reject the login attempt.
}
The stored hash contains the information needed for verification. Do not compare a newly generated hash with the stored value using ==.
Check Whether a Hash Needs Updating
if (password_needs_rehash($storedHash, PASSWORD_DEFAULT)) {
$newHash = password_hash($submittedPassword, PASSWORD_DEFAULT);
// Save $newHash for this account.
}
This helps applications refresh hashes when the default algorithm or its settings change.
Additional Security
Use HTTPS, rate-limit login attempts, protect password reset flows, and avoid revealing whether an account exists. Never log passwords.
Summary
Use password_hash() when setting a password, password_verify() when checking it, and password_needs_rehash() to keep stored hashes current.