PHP
Securely Hash Passwords using `password_hash`
Learn to securely hash user passwords in PHP using the built-in `password_hash()` function, protecting against Rainbow Table attacks and making brute-force attempts harder.
<?php
function hashPassword(string $password): string
{
// Use PASSWORD_BCRYPT as it's currently a strong, widely-supported algorithm.
// password_hash automatically generates a salt.
return password_hash($password, PASSWORD_BCRYPT);
}
function verifyPassword(string $password, string $hashedPassword): bool
{
return password_verify($password, $hashedPassword);
}
// Example usage:
$userPassword = 'mySuperSecurePassword123!';
$hashed = hashPassword($userPassword);
echo "Hashed Password: " . $hashed . "
";
if (verifyPassword($userPassword, $hashed)) {
echo "Password verified successfully.
";
} else {
echo "Password verification failed.
";
}
// Simulating a wrong password attempt
if (verifyPassword('wrongPassword', $hashed)) {
echo "Wrong password verified (ERROR)!
";
} else {
echo "Wrong password not verified (CORRECT).
";
}
?>
How it works: This snippet demonstrates the secure way to hash and verify user passwords in PHP using the `password_hash()` and `password_verify()` functions. `password_hash()` uses a strong, one-way hashing algorithm (like bcrypt by default) and automatically generates a unique salt for each password, making rainbow table attacks ineffective and increasing the difficulty of brute-force attacks. `password_verify()` safely compares a plain-text password against a hash, preventing timing attacks.