PHP Security

Password Hashing and Verification in PHP

Store passwords safely with PHP password_hash() and verify them with password_verify(), without storing plaintext passwords.

Password Hashing and Verification in PHP

Applications should never store user passwords in plaintext. PHP provides password hashing functions that create secure password hashes and verify submitted passwords later.

Hash a Password

Use password_hash() to create a hash. Let PHP manage the salt and algorithm parameters.

$password = $_POST["password"] ?? "";

$hash = password_hash($password, PASSWORD_DEFAULT);

Store the resulting hash in a database column large enough to accommodate future algorithm changes. A VARCHAR(255) column is a common choice.

Verify a Password

When a user signs in, retrieve the stored hash for the account and use password_verify().

if (password_verify($submittedPassword, $storedHash)) {
    // Password is valid.
} else {
    // Reject the login attempt.
}

Do not compare password hashes using ==, and do not attempt to recreate the hash manually. The verification function handles the salt and algorithm information embedded in the stored hash.

Rehash When Needed

PHP can tell you whether a stored hash should be updated using password_needs_rehash().

if (password_needs_rehash($storedHash, PASSWORD_DEFAULT)) {
    $newHash = password_hash($submittedPassword, PASSWORD_DEFAULT);
    // Save the new hash for this user.
}

Additional Account Protections

Use HTTPS, rate-limit login attempts, provide secure password reset flows, and avoid revealing whether a username or email address exists. Consider multi-factor authentication for sensitive accounts. Never log passwords or include them in error messages.

Conclusion

Use password_hash() when creating or changing passwords and password_verify() when authenticating users. These built-in functions are safer and more maintainable than custom hashing schemes.

Share this page Help other developers discover this resource.