PHP
Securely Hash and Verify Passwords with `password_hash()`
Implement robust password security for user authentication by hashing passwords using PHP's `password_hash()` with `PASSWORD_BCRYPT` and verifying them securely.
<?php
// --- Hashing a new password ---
$plainTextPassword = "myStrongPassword123!"; // Password submitted by the user
$hashedPassword = password_hash($plainTextPassword, PASSWORD_BCRYPT);
if ($hashedPassword === false) {
// Handle error: password_hash failed (e.g., low memory)
die("Password hashing failed.");
}
// Store $hashedPassword in your database
echo "Hashed Password: " . $hashedPassword . "
";
// --- Verifying a password during login ---
$passwordAttempt = "myStrongPassword123!"; // Password provided by user at login
$storedHashedPassword = $hashedPassword; // Retrieve this from your database for the given user
if (password_verify($passwordAttempt, $storedHashedPassword)) {
echo "Password is valid! User logged in.
";
// Optional: Rehash if the algorithm or cost changed to keep hashes up-to-date
if (password_needs_rehash($storedHashedPassword, PASSWORD_BCRYPT, ['cost' => 12])) {
$newHashedPassword = password_hash($passwordAttempt, PASSWORD_BCRYPT, ['cost' => 12]);
// Update the user's password in the database with $newHashedPassword
echo "Password rehashed and updated.
";
}
} else {
echo "Invalid password. Access denied.
";
}
// Example with an incorrect password
$incorrectAttempt = "wrongPassword";
if (password_verify($incorrectAttempt, $storedHashedPassword)) {
echo "Incorrect password is valid! (This should not happen)
";
} else {
echo "Incorrect password correctly rejected.
";
}
?>
How it works: Storing plain-text passwords is a critical security vulnerability. PHP's `password_hash()` function provides a secure way to hash passwords using strong, adaptive hashing algorithms like bcrypt (the default for `PASSWORD_BCRYPT`). It automatically generates a salt and applies a suitable work factor (cost) to make brute-force attacks computationally expensive. `password_verify()` then securely compares a plain-text password attempt against a stored hash without revealing the original password, and `password_needs_rehash()` helps keep password hashes up-to-date with current security standards.