PHP
Securely Hash and Verify Passwords with Bcrypt in PHP
Implement robust password security by using PHP's built-in `password_hash()` and `password_verify()` functions with Bcrypt, safeguarding user credentials against brute-force and rainbow table attacks.
<?php
// --- Step 1: Hashing a new password ---
$userPassword = 'mySecretPassword123!'; // Password received from user input (e.g., registration form)
// Generate a secure hash using the default (Bcrypt) algorithm
// password_hash automatically generates a salt
$hashedPassword = password_hash($userPassword, PASSWORD_DEFAULT);
if ($hashedPassword === false) {
die('Password hashing failed!');
}
echo "Original password: " . $userPassword . "
";
echo "Hashed password: " . $hashedPassword . "
";
// --- Step 2: Verifying a password (e.g., during login) ---
$loginAttemptPassword = 'mySecretPassword123!'; // Password entered by user during login
$storedHashedPassword = $hashedPassword; // Retrieve this from your database for the given user
if (password_verify($loginAttemptPassword, $storedHashedPassword)) {
echo "Password verified successfully! User can log in.
";
// --- Step 3 (Optional): Re-hashing if the algorithm or cost needs updating ---
// This is important for future-proofing your password storage
if (password_needs_rehash($storedHashedPassword, PASSWORD_DEFAULT)) {
$newHashedPassword = password_hash($loginAttemptPassword, PASSWORD_DEFAULT);
// Update the user's password in the database with $newHashedPassword
echo "Password re-hashed to a stronger algorithm/cost.
";
}
} else {
echo "Incorrect password. Login failed.
";
}
// Example of incorrect password attempt
$incorrectPassword = 'wrongPassword';
if (!password_verify($incorrectPassword, $storedHashedPassword)) {
echo "Incorrect password '" . $incorrectPassword . "' failed verification.
";
}
?>
How it works: This snippet demonstrates the correct and secure way to handle user passwords using PHP's built-in `password_hash()` and `password_verify()` functions. `password_hash()` uses a strong, adaptive hashing algorithm (Bcrypt by default) to create a unique hash for each password, automatically generating and incorporating a random salt. This prevents rainbow table attacks and makes brute-force attacks significantly harder. `password_verify()` then safely compares a provided password against a stored hash without exposing the original password, ensuring robust authentication and data security. The `password_needs_rehash()` function allows for updating hashes when algorithms or cost factors improve.