PHP Password Hashing

πŸ” PHP Password Hashing – Secure User Authentication

Storing plain-text passwords? STOP RIGHT THERE! 🚨

If a hacker steals your database, they can see every password. 😱 Instead, we hash passwords using PHP’s password_hash() function, making them unreadable and secure. πŸ’ͺ


πŸš€ What is Password Hashing?

Hashing converts a password into a fixed-length string that cannot be reversed. Even if someone steals the hash, they can’t retrieve the original password.

βœ… Example: Hashing a Password

Let’s hash a password using password_hash() with the BCRYPT algorithm.

<?php
$password = "supersecure123"; // User's password
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

echo "Hashed Password: " . $hashedPassword;
?>

Try It Now

πŸ” What’s happening?
– The function password_hash() encrypts the password.
– Even if you run this code again, the hash will be different! πŸ”„


πŸ”‘ How to Verify a Password?

When a user logs in, we verify their entered password against the stored hash.

βœ… Example: Password Verification

Let’s check if a password matches the stored hash using password_verify().

<?php
$storedHash = '$2y$10$examplehashedpasswordvalue...'; // Stored in database
$enteredPassword = "supersecure123"; // User input

if (password_verify($enteredPassword, $storedHash)) {
    echo "βœ… Password is correct!";
} else {
    echo "❌ Incorrect password!";
}
?>

Try It Now

πŸ›‘οΈ Why is this secure?
password_verify() compares the input with the stored hash.
– The hash is never reversed, making it impossible for hackers to retrieve the original password. πŸ”


♻️ When to Rehash Passwords?

If your hashing algorithm changes, rehash passwords using password_needs_rehash().

βœ… Example: Rehashing Passwords

<?php
$storedHash = '$2y$10$examplehashedpasswordvalue...'; // Stored hash

if (password_needs_rehash($storedHash, PASSWORD_DEFAULT)) {
    $newHash = password_hash("supersecure123", PASSWORD_DEFAULT);
    echo "Password rehashed: " . $newHash;
}
?>

Try It Now

πŸ”„ Why rehash?
– If PHP improves its hashing algorithm, old hashes become outdated.
Rehash ensures better security for stored passwords.


🎯 Best Practices for Password Security

  • βœ… Always hash passwords before storing them.
  • βœ… Never store plain-text passwords! 🚫
  • βœ… Use password_hash() for hashing.
  • βœ… Use password_verify() for checking passwords.
  • βœ… Rehash passwords when updating your system.

πŸš€ Next Steps

Try modifying the examples and implementing secure authentication in your PHP projects today! πŸ”₯