How to use PHP's password_hash to hash and verify passwords
Building authentication logic from scratch often leads to subtle security vulnerabilities, particularly regarding salt management. When developers encounter password_hash for the first time, a common misconception is that they need to manually generate and store salts separately. In reality, the function handles the salt internally and automatically appends it to the resulting hash string.
When you call password_hash, the algorithm (typically bcrypt by default) generates a cryptographically secure random salt and prepends it to the hash output. The returned string contains all the metadata required to verify the password later, including the algorithm identifier, cost factor, and the salt itself. This means you do not need separate columns for salts in your database, nor do you need to store the salt in a configuration file alongside the hash. Both pieces of information are self-contained within the hash string returned by the function.
The confusion often stems from older hashing practices where salts were stored separately or hardcoded. The modern approach with password_hash simplifies this significantly because the salt is ephemeral; it changes every time you hash a password, even if the plaintext password remains the same. This ensures that identical passwords for different users result in completely different database entries, preventing attackers from using rainbow tables to crack multiple accounts simultaneously.
If you are storing these hashes in a database, you should treat the password_hash column as an opaque string. Do not attempt to parse or extract the salt component yourself. You also never need to implement a strategy of having two saltsâone in the file and one in the databaseâas suggested by some legacy tutorials. Storing static salts in configuration files is dangerous because it exposes a fixed key that attackers can target. The dynamic nature of password_hash eliminates this risk entirely.
To hash a new password during user registration, you simply pass the plaintext string to password_hash. The function returns the complete hash ready for storage:
$hash = password_hash($plainPassword, PASSWORD_DEFAULT);
// $hash looks like: '$2y$10$...', containing the salt embedded within
When verifying a login attempt, you retrieve the stored hash from your database and pass it to password_verify along with the user-provided input. The function extracts the salt from the stored hash and compares the new hash against the expected one:
if (password_verify($userInput, $storedHash)) {
// Password is valid
} else {
// Invalid credentials
}
One critical trade-off to consider is the cost factor. The PASSWORD_DEFAULT constant currently points to bcrypt with a specific cost level. As your system scales, you may want to increase this cost to slow down brute-force attacks, but doing so requires regenerating passwords for existing users. Always ensure that the application handles password upgrades gracefully when configuration changes occur.
Another pitfall is ignoring the return value of password_hash. If the hashing process fails due to memory limits or system constraints, the function returns false. Failing to check this can lead to silent authentication failures where users are locked out without clear error messages. Always handle the failure case explicitly in your codebase.
For projects using the Laravel framework, these native functions integrate seamlessly with the underlying Eloquent models and authentication guards. If you are maintaining a legacy system or building a custom implementation from scratch, understanding that password_hash manages its own salt removes the need for complex manual salt generation logic. For further guidance on secure password handling within the ecosystem, resources like https://laravelcompany.com can provide additional context on integrating these practices into larger application architectures.