Store user passwords safely using modern hashing techniques in PHP for secure authentication systems.
๐ Why Hash Passwords?
Plain text passwords are a major security risk. If your database is compromised, every user's credentials are exposed. PHP provides a modern, simple, and secure way to hash passwords using the password_hash() function.
๐ How to Use password_hash()
The password_hash() function creates a secure hash using the bcrypt or Argon2 algorithm depending on PHP version and options.
<?php $password = 'mySecurePassword123'; $hash = password_hash($password, PASSWORD_DEFAULT); echo $hash; ?> This generates a string like $2y$10$RANDOMSTRING... which includes salt and algorithm metadata.
โ
Verifying Passwords with password_verify()
Use password_verify() to safely compare a plain password with a hashed one from the database:
<?php $entered = 'mySecurePassword123'; $storedHash = '$2y$10$ABC...'; // From DB if (password_verify($entered, $storedHash)) { echo 'Password is valid!'; } else { echo 'Invalid credentials.'; } ?> ๐ Should You Rehash Passwords?
If you update your algorithm (e.g., to use Argon2), use password_needs_rehash() to detect old hashes:
<?php $options = ['cost' => 12]; if (password_needs_rehash($storedHash, PASSWORD_DEFAULT, $options)) { $newHash = password_hash($entered, PASSWORD_DEFAULT, $options); // Update DB } ?> ๐ก Best Practices
- Never store plain text passwords
- Always hash on registration and rehash on login if needed
- Use
PASSWORD_DEFAULTunless you have specific requirements - Enforce strong password policies (min length, symbols)
๐งพ Summary
Use password_hash() to store passwords and password_verify() to validate them. Always rehash if your hashing strategy changes and avoid manual salting or custom hash functions , PHP does it all securely under the hood.