PHP
Securely Hash Passwords with PHP's password_hash
Implement robust password security by hashing user passwords using PHP's `password_hash()` and `password_verify()` with strong algorithms like `PASSWORD_ARGON2ID` or `PASSWORD_BCRYPT`.
<?php
// 1. Hashing a password for storage
$user_password = "mySecretPassword123!";
// Choose the strongest available algorithm.
// PASSWORD_ARGON2ID is currently recommended if available (PHP 7.2+ with Argon2 support).
// Fallback to PASSWORD_BCRYPT if Argon2 is not available or preferred.
$hash_algorithm = defined('PASSWORD_ARGON2ID') ? PASSWORD_ARGON2ID : PASSWORD_BCRYPT;
// Optional: Configure cost for bcrypt (higher cost means slower hashing, more secure)
// For Argon2, parameters like 'memory_cost', 'time_cost', 'threads' can be set.
$options = [
'cost' => 12 // Default is 10. A cost of 12 is generally good. Adjust based on server performance.
];
$hashed_password = password_hash($user_password, $hash_algorithm, $options);
echo "Original Password: " . $user_password . "
";
echo "Hashed Password: " . $hashed_password . "
";
// 2. Verifying a password during login
$provided_password = "mySecretPassword123!"; // Password entered by user
$incorrect_password = "wrongPassword";
if (password_verify($provided_password, $hashed_password)) {
echo "Password verification successful for provided_password! User can log in.
";
// 3. Rehash if necessary (e.g., if cost factor changes or a stronger algorithm becomes available)
if (password_needs_rehash($hashed_password, $hash_algorithm, $options)) {
$new_hashed_password = password_hash($provided_password, $hash_algorithm, $options);
echo "Password needed rehash. New hash: " . $new_hashed_password . "
";
// Update the stored hash in your database
}
} else {
echo "Password verification failed for provided_password.
";
}
if (password_verify($incorrect_password, $hashed_password)) {
echo "Password verification successful for incorrect_password! (This should not happen)
";
} else {
echo "Password verification failed for incorrect_password. Correct behavior.
";
}
?>
How it works: This PHP snippet demonstrates best practices for securely handling user passwords. It uses `password_hash()` to create a cryptographically strong hash of a password, suitable for storage. `PASSWORD_ARGON2ID` (or `PASSWORD_BCRYPT` as a fallback) is preferred for its robustness against brute-force attacks. The `cost` option allows adjusting the computational expense, making attacks harder. `password_verify()` is used to safely check a user-provided password against its stored hash without risking timing attacks. `password_needs_rehash()` helps maintain security by prompting for rehashing if the algorithm or cost factors have been updated.