Creating a password hash
suggest changeCreate password hashes with password_hash(). PASSWORD_DEFAULT lets PHP select a secure algorithm and allows that choice to improve in future PHP releases.
$hashedPassword = password_hash($plaintextPassword, PASSWORD_DEFAULT);
Do not generate or pass a salt yourself. PHP generates a cryptographically secure random salt and stores the algorithm, cost, and salt in the returned hash.
Verify a submitted password with password_verify():
if (password_verify($submittedPassword, $hashedPassword)) {
// The password is valid.
}
Because the meaning of PASSWORD_DEFAULT may change, allow enough room for hashes to grow; a VARCHAR(255) column is a common choice. After a successful login, password_needs_rehash() can detect hashes that should be upgraded to the current algorithm or options:
if (password_verify($submittedPassword, $hashedPassword)) {
if (password_needs_rehash($hashedPassword, PASSWORD_DEFAULT)) {
$hashedPassword = password_hash($submittedPassword, PASSWORD_DEFAULT);
// Persist the replacement hash.
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents