Storing user passwords in plain text is one of the biggest security risks a developer can take. If your database is ever compromised, hackers would have instant access to all user accounts. To prevent this, PHP provides a native Password Hashing API to secure credentials.
When a user registers, you should hash their password before saving it to the database. The password_hash() function handles everything, including salting and choosing a strong algorithm (usually BCrypt).
<?php
$password = "mySecretPassword123";
// Hash the password using the default algorithm
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
echo $hashedPassword;
// Output: $2y$10$QjSHW965iaZp... (a long, secure string)
?>
When a user tries to log in, you retrieve the hashed password from the database and compare it to what the user just typed using password_verify().
<?php
$userTypedPassword = "mySecretPassword123";
$hashedFromDatabase = "$2y$10$QjSHW965iaZp..."; // The hash you saved earlier
if (password_verify($userTypedPassword, $hashedFromDatabase)) {
echo "Password is valid! Access granted.";
} else {
echo "Invalid password. Access denied.";
}
?>
password_hash() -> Store Hash in DB.password_verify().md5() or sha1() for passwords. They are extremely fast, which makes them easy for hackers to crack using "Brute Force" attacks.