PHP
Secure User Passwords with Modern Hashing Algorithms in PHP
Learn to securely hash user passwords using PHP's `password_hash()` with recommended algorithms, protecting against brute-force and rainbow table attacks.
<?php
// Registering a new user
$userPassword = 'mySecretPassword123';
$hashedPassword = password_hash($userPassword, PASSWORD_ARGON2ID); // Or PASSWORD_BCRYPT
if ($hashedPassword === false) {
die('Password hashing failed!');
}
// Store $hashedPassword in your database
echo "Hashed Password: " . $hashedPassword . "
";
// Verifying a user's login attempt
$loginAttemptPassword = 'mySecretPassword123'; // User input
$storedHashedPassword = $hashedPassword; // Retrieved from database
if (password_verify($loginAttemptPassword, $storedHashedPassword)) {
echo "Password verified successfully! User logged in.
";
} else {
echo "Invalid password. Access denied.
";
}
// Example of re-hashing if algorithm/cost changes (optional but good practice)
// In a real application, you'd check this on login
if (password_needs_rehash($storedHashedPassword, PASSWORD_ARGON2ID)) {
$newHashedPassword = password_hash($loginAttemptPassword, PASSWORD_ARGON2ID);
echo "Password re-hashed to: " . $newHashedPassword . "
";
// Update the database with $newHashedPassword
}
How it works: This snippet demonstrates how to securely hash and verify user passwords in PHP using the `password_hash()` and `password_verify()` functions. `password_hash()` automatically generates a salt and applies a strong, computationally intensive hashing algorithm (like `ARGON2ID` or `BCRYPT`), making brute-force attacks difficult. `password_verify()` safely compares a plain-text password with a hash, preventing timing attacks. `password_needs_rehash()` helps keep password security up-to-date.