π 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; ?>
π 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!"; } ?>
π‘οΈ 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; } ?>
π 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! π₯