How to store and verify a password
Short answer
On registration store the hash in the database, not the password itself:
<?php
$hash = password_hash('secret-password', PASSWORD_DEFAULT);
echo strlen($hash) >= 60 ? 'hash created' : 'error';Output:
hash createdChecking on login
password_verify() compares the entered password with the hash from the database:
<?php
$hash = password_hash('secret-password', PASSWORD_DEFAULT);
var_dump(password_verify('secret-password', $hash));
var_dump(password_verify('wrong', $hash));Output:
bool(true)
bool(false)Rehashing
The default algorithm changes over time. After a successful login check whether the hash needs recomputing:
<?php
$hash = password_hash('secret-password', PASSWORD_DEFAULT);
var_dump(password_needs_rehash($hash, PASSWORD_DEFAULT));Output:
bool(false)Functions used in this recipe
- password_hash — Creates a password hash for storing in a database.
- password_verify — Checks whether a password matches a hash.
- random_bytes — Returns cryptographically secure random bytes.