PHP
Secure Password Hashing and Verification
Implement robust password security in PHP using `password_hash()` for hashing and `password_verify()` for secure verification, protecting user credentials.
// Hashing a password
$password = "mySecretPassword123!";
$hashed_password = password_hash($password, PASSWORD_BCRYPT);
echo "Original Password: " . $password . "
";
echo "Hashed Password: " . $hashed_password . "
";
// Verifying a password
$user_attempt = "mySecretPassword123!"; // Password provided by user during login
if (password_verify($user_attempt, $hashed_password)) {
echo "Password is valid. User logged in successfully!
";
// Optionally, rehash if the algorithm or cost has changed
if (password_needs_rehash($hashed_password, PASSWORD_BCRYPT)) {
$new_hashed_password = password_hash($user_attempt, PASSWORD_BCRYPT);
echo "Password rehashed with updated algorithm/cost.
";
// Update $new_hashed_password in your database for this user
}
} else {
echo "Invalid password. Access denied.
";
}
How it works: This PHP snippet illustrates the correct and secure way to handle user passwords using PHP's built-in `password_hash()` and `password_verify()` functions. `password_hash()` generates a strong, one-way hash with a randomly generated salt and a suitable algorithm (like `PASSWORD_BCRYPT`). `password_verify()` safely compares a provided plain-text password against a stored hash without exposing the original password, safeguarding against brute-force attacks and database breaches. `password_needs_rehash()` helps keep hashes up-to-date with current security standards.