Secure hash and salt for PHP passwords
To securely hash and salt passwords in PHP, you can use the password_hash
function. This function uses the bcrypt
hashing algorithm, which is secure and resistant to attacks.
Here's an example of how to use it:
<?php
$password = 'mypassword';
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
echo $hashed_password;
The password_hash
function generates a random salt for you, so you don't have to worry about generating and storing a salt yourself. It also hashes the password using a strong hashing algorithm, so you don't have to worry about choosing a hashing algorithm or implementing it yourself.
To verify a password, you can use the password_verify
function:
<?php
$password = 'mypassword';
$hashed_password = '$2y$10$abcdefghijklmnopqrstuvwxyz';
if (password_verify($password, $hashed_password)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
This is the recommended way to hash and verify passwords in PHP. It's secure and easy to use.