Using password_hash to Hash and Store Passwords in PHP
- 2 minutes read
PHP offers a very powerful password_hash
function, which will create a one-way hash of a string. It’s often used for hashing passwords and access tokens.
We can pass an algorithm to password_hash
, but I’ll be focusing on PASSWORD_DEFAULT
, which is a built-in algorithm designed to change over time as stronger algorithms are developed.
If you want to read about the other built-in algorithms that PHP offers, the official password hashing documentation explains each of them.
Anyway, password_hash
is fairly straightforward. The first parameter is the string to hash (in this case, “dragon123”). The second parameter is the algorithm to hash the string with.
$password = 'dragon123';
$hash = password_hash($password, PASSWORD_DEFAULT);
// As of writing this, $hash returns this monstrous string:
// "$2y$10$WIj56IGASADOa26io1AzeuMRvp3SKdYu8saCU.6.1xDpnr3w6xECS"
Remember, the PASSWORD_DEFAULT
algorithm is subject to change over time, so this code might return a different result for you in the future.
Furthermore, I want to echo the official documentation’s suggestion to ensure your hashed password database column supports strings of up to 255 characters in length, likely ensuring future compatibility.
Verifying hashed passwords with password_verify
Verifying a hashed password is just as simple, thanks to password_verify
.
The first parameter is the plaintext string to check, and the second parameter is the hashed string to check the first string against.
$password = 'dragon123';
$hash = '$2y$10$WIj56IGASADOa26io1AzeuMRvp3SKdYu8saCU.6.1xDpnr3w6xECS';
$result = password_verify($password, $hash);
This function will return a boolean, either true
or false
, depending on whether the first string is valid:
if ($result === true) {
echo "Successfully authenticated."
} else {
echo "Invalid password."
}
If dragon123
is passed, $result
will be true
. However, if dragon456
or something else is passed, $result
will be false
.
Conclusion
While this is certainly isn’t state-of-the-art, it’s a great step for most small websites and startups, that is at least certainly far ahead of using a custom salt (let alone storing passwords in plaintext).