Password Hashing & Salting

Storing passwords as plain text is unforgivable. Always transform them into secure hashes before persisting them to your database. PHP’s password_hash function uses strong algorithms and automatically generates a salt for you.

1. Generating a hash

To hash a password, call password_hash with PASSWORD_DEFAULT. This will choose the best algorithm available (currently bcrypt) and embed the salt in the output.

$hash = password_hash($plainPassword, PASSWORD_DEFAULT); // store $hash in your users table

2. Verifying passwords

To check a user’s password, fetch the stored hash and call password_verify. It will extract the salt and compare the hashes safely.

if (password_verify($enteredPassword, $storedHash)) { // password correct } else { // invalid credentials }

3. Rehashing when algorithms change

Algorithms evolve. Use password_needs_rehash to migrate hashes to stronger algorithms when they become available.