To hash a password in PHP, you can use the password_hash()
function. Here’s an example of how to use it:
$password = "password123"; // replace with actual password
$hashed_password = password_hash($password, PASSWORD_DEFAULT, ['cost' => 12]);
This will hash the password using the default algorithm (currently bcrypt) and a cost factor of 12. The cost factor determines how many iterations of the hashing algorithm are applied, making it more difficult for attackers to crack the password.
You can then store the hashed password in your database or other storage mechanism.
To verify a password later, you can use the password_verify()
function:
$submitted_password = "password123"; // replace with password submitted by user
if (password_verify($submitted_password, $hashed_password)) {
// password is correct
} else {
// password is incorrect
}
This function takes the submitted password and the previously hashed password as arguments, and returns true
if the submitted password matches the hashed password, or false
otherwise.
Note: The PASSWORD_DEFAULT
constant uses the strongest available algorithm at the time of implementation, but this can change over time as new algorithms are added and old ones are deprecated. It’s a good idea to periodically review and update your password hashing practices to ensure they are up-to-date and secure.