How to Hash Password in PHP Securely with password_hash()
In PHP, you can hash a password securely using the
password_hash() function, which automatically applies a strong hashing algorithm and salt. To verify a password later, use password_verify() to check if the input matches the hashed password.Syntax
The password_hash() function creates a hashed password string. It takes the plain password and a hashing algorithm constant as arguments.
password_hash(string $password, int $algo, array $options = [])$password: The plain text password to hash.$algo: The hashing algorithm, usuallyPASSWORD_DEFAULTfor the best current algorithm.$options: Optional array to set options likecost(work factor).
The password_verify() function checks if a plain password matches a hashed password.
php
$hashedPassword = password_hash('your_password', PASSWORD_DEFAULT); if (password_verify('your_password', $hashedPassword)) { echo 'Password is valid!'; } else { echo 'Invalid password.'; }
Output
Password is valid!
Example
This example shows how to hash a password and then verify it. It prints whether the password is valid or not.
php
<?php // Hash the password $plainPassword = 'mySecret123'; $hashedPassword = password_hash($plainPassword, PASSWORD_DEFAULT); echo "Hashed password: " . $hashedPassword . "\n"; // Verify the password if (password_verify('mySecret123', $hashedPassword)) { echo "Password is valid!"; } else { echo "Invalid password."; } ?>
Output
Hashed password: $2y$10$... (hash string)
Password is valid!
Common Pitfalls
- Do not use simple hashing functions like
md5()orsha1()for passwords; they are insecure. - Always use
password_hash()withPASSWORD_DEFAULTto get a strong, up-to-date algorithm. - Never store plain passwords or unhashed passwords in your database.
- Do not try to manually add salt;
password_hash()handles it automatically. - Always verify passwords with
password_verify(), not by comparing hashes directly.
php
<?php // Wrong way (do NOT use): $hash = md5('password123'); // insecure and no salt // Right way: $hash = password_hash('password123', PASSWORD_DEFAULT); ?>
Quick Reference
Use this quick guide when hashing passwords in PHP:
- Hashing:
password_hash($password, PASSWORD_DEFAULT) - Verifying:
password_verify($inputPassword, $hashedPassword) - Never: use
md5(),sha1(), or manual salts - Store: only the hashed password string in your database
Key Takeaways
Always use password_hash() with PASSWORD_DEFAULT to hash passwords securely.
Verify passwords using password_verify() to check user input against stored hashes.
Never use outdated hashing functions like md5() or sha1() for passwords.
Do not manually add salt; password_hash() manages it automatically.
Store only hashed passwords, never plain text, in your database.