What are the best practices for securely storing and comparing hashed passwords in PHP?
When storing and comparing hashed passwords in PHP, it is important to use a strong hashing algorithm like bcrypt, properly salt the passwords before hashing, and securely store the salt along with the hashed password. When comparing passwords, always use a secure comparison function like password_verify to prevent timing attacks.
// Storing a hashed password
$password = 'password123';
$salt = random_bytes(16); // Generate a random salt
$hashedPassword = password_hash($password . $salt, PASSWORD_BCRYPT);
// Comparing a hashed password
$userInput = 'password123';
if(password_verify($userInput . $salt, $hashedPassword)) {
echo 'Password is correct!';
} else {
echo 'Password is incorrect!';
}
Related Questions
- What are the potential security risks associated with using session_register() and session_name() in PHP scripts?
- What are common pitfalls when using $_Session variables in PHP for navigation?
- What potential issues can arise when upgrading from PHP 7.4.22 to PHP 8.0.9 in terms of code compatibility?