PHP
Securely Hash and Verify Passwords with PHP
Learn to securely hash and verify user passwords using PHP's built-in `password_hash` and `password_verify` functions, leveraging strong, modern cryptographic algorithms.
<?php
// --- Hashing a password ---
function hashPassword($plainPassword) {
// Use PASSWORD_DEFAULT for the strongest available algorithm (currently bcrypt)
// password_hash automatically generates a secure salt
$hashedPassword = password_hash($plainPassword, PASSWORD_DEFAULT);
return $hashedPassword;
}
// --- Verifying a password ---
function verifyPassword($plainPassword, $hashedPassword) {
return password_verify($plainPassword, $hashedPassword);
}
// --- Example Usage ---
$userProvidedPassword = "MySecretPa$$w0rd";
// 1. Store the hashed password (e.g., in a database)
$storedHashedPassword = hashPassword($userProvidedPassword);
echo "Hashed Password: " . $storedHashedPassword . "
";
// 2. Later, when a user tries to log in:
$loginAttemptPassword = "MySecretPa$$w0rd"; // User enters this
$incorrectPassword = "WrongPassword";
if (verifyPassword($loginAttemptPassword, $storedHashedPassword)) {
echo "Login successful! Password matched.
";
} else {
echo "Login failed! Password did not match.
";
}
if (verifyPassword($incorrectPassword, $storedHashedPassword)) {
echo "Login successful (unexpected!).
";
} else {
echo "Login failed! Incorrect password handled.
";
}
?>
How it works: This PHP snippet demonstrates the secure way to handle user passwords using `password_hash` for hashing and `password_verify` for verification. `password_hash` automatically generates a cryptographically secure salt and applies a strong hashing algorithm (like bcrypt, specified by `PASSWORD_DEFAULT`). This makes rainbow table attacks and brute-force attacks significantly harder. `password_verify` securely compares a plain-text password against a hash, making it impossible to reveal the original password even if the hash is compromised. It also handles algorithm upgrades automatically.