Password hashing
password_hash
Function password_hash turns a plain password into a salted one way hash. Store only the hash in the database, never the original text.
Use the default algorithm unless you have a clear reason to pick another. The function generates a fresh random salt on every call.
$hash = password_hash("secret123", PASSWORD_DEFAULT);
echo $hash;
password_verify
Function password_verify compares a login attempt against the stored hash. It handles salts and algorithm details for you.
It returns a plain boolean, so branch on true or false. Keep error messages generic to avoid leaking which accounts exist.
if (password_verify("secret123", $hash)) {
echo "welcome";
}
needs_rehash
Algorithms and cost settings change over time. Function password_needs_rehash tells you when a stored hash no longer matches current policy.
Check right after a successful login, when the plain password is still available. Rehash and save the new value at once.
if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
$hash = password_hash("secret123", PASSWORD_DEFAULT);
echo "updated";
}
Algo upgrades
PHP ships several algorithms behind one stable API. The default has changed across versions while the function names stayed the same.
Probe for modern options with defined before using them. Fall back to the default when a constant is missing.
echo PASSWORD_DEFAULT;
echo PASSWORD_BCRYPT;
if (defined("PASSWORD_ARGON2ID")) {
echo "argon2 ready";
}
Next: XSS and CSRF
Автор статьи: Arthur Isaev