PHP
Implement Secure Password Hashing and Verification
Discover how to securely hash and verify user passwords in PHP using the `password_hash()` and `password_verify()` functions, a critical step for robust user authentication.
<?php
// Function to hash a password
function hash_password(string $password): string {
// PASSWORD_DEFAULT uses the strongest available algorithm (currently bcrypt)
// and handles salt generation automatically.
return password_hash($password, PASSWORD_DEFAULT);
}
// Function to verify a password against a hash
function verify_password(string $password, string $hash): bool {
return password_verify($password, $hash);
}
// Usage example:
// $user_input_password = "mySecretPassword123!";
// $hashed_password = hash_password($user_input_password);
// echo "Hashed Password: " . $hashed_password . "
";
// // When a user tries to log in:
// $login_attempt_password = "mySecretPassword123!";
// if (verify_password($login_attempt_password, $hashed_password)) {
// echo "Password verified successfully!
";
// } else {
// echo "Invalid password.
";
// }
?>
How it works: This PHP snippet illustrates the correct way to handle user passwords. The `hash_password` function uses `password_hash(PASSWORD_DEFAULT)` to create a strong, one-way hash of a password, automatically incorporating a unique salt and using the recommended hashing algorithm (currently bcrypt). This protects against rainbow table attacks and makes brute-forcing significantly harder. The `verify_password` function then safely compares a user's login attempt with the stored hash, preventing direct hash comparisons and ensuring only the original password can be validated.