To hash passwords in PHP using the bcrypt algorithm, you can use the password_hash() function, and to verify hashed passwords, you can use the password_verify() function. Here's a step-by-step example:
- Hashing a Password:
php
// User's password to be hashed
$password = "user_password";
// Hash the password using bcrypt
$hashedPassword = password_hash($password, PASSWORD_BCRYPT);
// Store $hashedPassword in your database
In the code above:
- We have the plain text password in the variable
$password. - We use the
password_hash()function to hash the password using thePASSWORD_BCRYPTalgorithm, which is a strong choice for password hashing. - The resulting hash is stored in the variable
$hashedPassword, and you should store this value in your database.
- Verifying a Password:
php
// User's entered password for verification
$userEnteredPassword = "user_password";
// Hash retrieved from the database
$storedHashedPassword = "hash_retrieved_from_database";
// Verify if the entered password matches the stored hash
if (password_verify($userEnteredPassword, $storedHashedPassword)) {
// Password is correct
echo "Password is correct.";
} else {
// Password is incorrect
echo "Password is incorrect.";
}
In this code:
- We have the plain text password entered by the user in the variable
$userEnteredPassword. - We also have the hashed password retrieved from the database in the variable
$storedHashedPassword. - We use the
password_verify()function to check if the entered password matches the stored hash. If it matches, the password is correct; otherwise, it's incorrect.
Make sure to store and retrieve the hashed password from your database securely. Using bcrypt with password_hash() and password_verify() is a recommended approach for securely managing user passwords in PHP.
Comments
Post a Comment