PHP
Secure Password Hashing with PHP's `password_hash` (Bcrypt)
Learn to securely hash user passwords in PHP using the robust `password_hash` function with the BCrypt algorithm, protecting sensitive credentials from brute-force and rainbow table attacks.
<?php
// --- Hashing a password ---
function hashPassword($plainPassword) {
// PASSWORD_BCRYPT is the recommended algorithm.
// PASSWORD_DEFAULT constantly updates to the strongest available.
// 'cost' parameter determines the algorithmic complexity (higher = slower, more secure).
// Default cost is 10.
$options = [
'cost' => 12, // Adjust cost as hardware improves
];
return password_hash($plainPassword, PASSWORD_BCRYPT, $options);
}
// --- Verifying a password ---
function verifyPassword($plainPassword, $hashedPassword) {
return password_verify($plainPassword, $hashedPassword);
}
// Example Usage:
$userPassword = 'MySuperSecurePassword123!';
// Store this in your database
$hashedUserPassword = hashPassword($userPassword);
echo "Hashed Password: " . $hashedUserPassword . "
";
// When user tries to log in
$loginAttemptPassword = 'MySuperSecurePassword123!';
if (verifyPassword($loginAttemptPassword, $hashedUserPassword)) {
echo "Password verified successfully! User logged in.
";
} else {
echo "Invalid password. Access denied.
";
}
$wrongPassword = 'WrongPassword!';
if (verifyPassword($wrongPassword, $hashedUserPassword)) {
echo "This should not happen.
";
} else {
echo "Correctly denied wrong password.
";
}
// Check if re-hashing is needed (e.g., if cost changed or algorithm updated)
// if (password_needs_rehash($hashedUserPassword, PASSWORD_BCRYPT, ['cost' => 14])) {
// $newHashedPassword = hashPassword($userPassword); // Re-hash and update in DB
// echo "Password re-hashed with new cost: " . $newHashedPassword . "
";
// }
How it works: This PHP snippet demonstrates the secure way to handle user passwords using PHP's built-in `password_hash` and `password_verify` functions. It leverages the bcrypt algorithm (specified by `PASSWORD_BCRYPT`), which is computationally intensive and designed to be resistant to brute-force attacks and rainbow tables. The `cost` parameter allows you to adjust the hashing strength; a higher cost makes hashing slower, increasing protection. Passwords should always be hashed, never stored in plain text.