PHP has a small set of functions made for passwords. You never store the real password. You store a hash, which is a one-way scrambled version that cannot be turned back. password_hash() creates it, and password_verify() checks it at login.
A good password hash is slow on purpose and uses a random salt. PHP does both for you. The hash string even stores the algorithm, the cost and the salt, so a later check needs only the password and the hash.
If your database leaks, plain passwords are exposed at once. Hashes with a salt and a slow algorithm make each guess expensive.
Do not compare hashes with ==.
Each hash has its own salt, so two hashes of the same password differ. Always use password_verify().
Syntax
PHP Syntax
The usual pattern: hash at sign-up, verify at login, rehash when settings are old:
PHP
// Sign-up: store this string in the database
$hash = password_hash($password, PASSWORD_DEFAULT);
// Login: true when the typed password matches
if (password_verify($typed, $hash)) {
// Upgrade old hashes while you have the password
if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
$hash = password_hash($typed, PASSWORD_DEFAULT);
}
}
$info = password_get_info($hash); // algo, algoName, options
$algos = password_algos(); // PHP 7.4+
Call password_hash($password, PASSWORD_DEFAULT) and save the returned string. Never save the plain password. At login, use password_verify() with the typed password and the saved hash.
md5() and sha1() are fast and have no salt, so attackers can test huge numbers of guesses. password_hash() is slow on purpose and adds a random salt to every hash.
A constant that means the recommended algorithm. It is bcrypt today. PHP may switch it to a stronger one in a future version, so store hashes in a column of at least 255 characters.
A bcrypt hash is 60 characters. Other algorithms such as Argon2 produce longer strings, which is why 255 characters is the safe column size.
After a successful password_verify(), call password_needs_rehash(). If it returns true, create a new hash with password_hash() and save it in place of the old one.
You do not need your own salt. password_hash() creates one. A secret pepper is optional extra work and can be added by hashing with hash_hmac() first, but plain password_hash() is already a safe default.