What are common methods for securely storing and retrieving passwords from a SQL database in PHP?
When storing passwords in a SQL database in PHP, it is crucial to securely hash the passwords before saving them to the database. This helps protect user passwords in case of a data breach. One common method for securely storing passwords is to use the PHP password_hash() function to generate a hash of the password and then store this hash in the database. When retrieving passwords, you can use the password_verify() function to compare the user input password with the hashed password stored in the database to authenticate the user.
// Storing password securely in the database
$password = "user_password";
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Insert $hashed_password into the database
// Retrieving and verifying password
$user_input_password = "user_input_password";
// Retrieve hashed password from the database
$stored_hashed_password = "hashed_password_from_database";
// Compare user input password with hashed password
if (password_verify($user_input_password, $stored_hashed_password)) {
// Passwords match, user is authenticated
echo "Password is correct";
} else {
// Passwords do not match
echo "Password is incorrect";
}