How can the PHP script be improved to securely handle password hashing for user login?
The PHP script can be improved by using a secure hashing algorithm like bcrypt to hash user passwords. This helps protect user passwords from being easily cracked in case of a data breach. Additionally, salting the passwords before hashing adds an extra layer of security to prevent rainbow table attacks.
// Securely hash and salt user passwords using bcrypt
function hashPassword($password) {
$options = ['cost' => 12];
$salt = base64_encode(random_bytes(16));
$hashedPassword = password_hash($password . $salt, PASSWORD_BCRYPT, $options);
return $hashedPassword;
}
// Verify hashed password
function verifyPassword($password, $hashedPassword) {
$salt = substr($hashedPassword, -24);
return password_verify($password . $salt, $hashedPassword);
}
// Example usage
$userPassword = "user123";
$hashedPassword = hashPassword($userPassword);
// Verify password
if (verifyPassword($userPassword, $hashedPassword)) {
echo "Password is correct!";
} else {
echo "Password is incorrect!";
}
Related Questions
- What are some common mistakes or errors to avoid when using PHP to interact with a database and prevent duplicate entries?
- What are the potential drawbacks of storing information about new posts in an external table for each user in a PHP forum?
- What is the best way to ensure that variables in PHP have two decimal places?