Short answer: hash passwords with password_hash($password, PASSWORD_DEFAULT) when a user registers, store the result in a VARCHAR(255) column, and check logins with password_verify($input, $hash). Never use MD5, SHA1 or your own salt. The rest of this guide explains how it works, when to pick Argon2id over bcrypt, and how to upgrade old hashes safely.
What does password_hash() do?
password_hash() is PHP’s built-in function for creating a one-way password hash. It picks a secure algorithm, creates a random salt for you, and returns a single string that contains the algorithm, the cost settings and the salt. Because everything needed for verification is inside that string, you do not store a salt separately.
The function works with three main algorithm constants: PASSWORD_DEFAULT (currently bcrypt, and it may change in future PHP versions), PASSWORD_BCRYPT (always bcrypt, hashes start with $2y$) and PASSWORD_ARGON2ID (available when PHP is compiled with Argon2 support). You can read the full details in the official PHP password_hash() manual.
Basic example: register and login with password_hash() and password_verify()
This is the minimum safe pattern. It uses PDO prepared statements so the email and hash are never concatenated into SQL.
Registration
<?php
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $pdo->prepare('INSERT INTO users (email, password_hash) VALUES (:email, :hash)');
$stmt->execute([':email' => $email, ':hash' => $hash]);Login
<?php
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
$stmt = $pdo->prepare('SELECT id, password_hash FROM users WHERE email = :email');
$stmt->execute([':email' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user && password_verify($password, $user['password_hash'])) {
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
// login successful
} else {
// show a generic "invalid email or password" message
}Two details matter here. First, password_verify() does a timing-safe comparison, so never compare hashes yourself with ==. Second, show the same error for a wrong email and a wrong password, so attackers cannot find out which emails exist.
Bcrypt vs Argon2id in PHP
| Feature | Bcrypt (PASSWORD_BCRYPT) | Argon2id (PASSWORD_ARGON2ID) |
|---|---|---|
| Available since | PHP 5.5 | PHP 7.3 (needs Argon2 support in the build) |
| Main setting | cost (default 12 from PHP 8.4) | memory_cost, time_cost, threads |
| Memory-hard | No | Yes, which makes GPU cracking more expensive |
| Password length limit | 72 bytes | No practical limit |
| OWASP guidance | Acceptable, use a work factor of at least 10 | First choice, minimum 19 MiB memory, 2 iterations, 1 thread |
The numbers above follow the OWASP Password Storage Cheat Sheet. In practice: if your PHP build supports it and you control the server, choose Argon2id. If you run on shared hosting where Argon2 may be missing, bcrypt through PASSWORD_DEFAULT is still a solid choice.
How to use Argon2id in PHP
<?php
if (defined('PASSWORD_ARGON2ID')) {
$hash = password_hash($password, PASSWORD_ARGON2ID, [
'memory_cost' => 19456, // KiB, about 19 MiB
'time_cost' => 2,
'threads' => 1,
]);
} else {
// fall back to bcrypt if Argon2 is not available in this PHP build
$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
}Always check defined('PASSWORD_ARGON2ID') first, because PHP only provides the constant when Argon2 support is compiled in. Start with the OWASP minimums, then raise memory_cost or time_cost until one hash takes a noticeable but acceptable time on your server.
Choose a good bcrypt cost
Since PHP 8.4 the default bcrypt cost is 12 (it was 10 before). Every +1 doubles the work. The PHP manual shows a small benchmark that finds the highest cost that keeps hashing under roughly 350 ms on your hardware:
<?php
$timeTarget = 0.35; // seconds
$cost = 10;
do {
$cost++;
$start = microtime(true);
password_hash('test', PASSWORD_BCRYPT, ['cost' => $cost]);
$end = microtime(true);
} while (($end - $start) < $timeTarget);
echo 'Suggested cost: ' . $cost;Upgrade old hashes with password_needs_rehash()
Settings that are safe today may be too weak in a few years. password_needs_rehash() tells you when a stored hash does not match your current algorithm or cost. Run it right after a successful login, when you have the plain password available for a moment:
<?php
if (password_verify($password, $user['password_hash'])) {
if (password_needs_rehash($user['password_hash'], PASSWORD_ARGON2ID)) {
$newHash = password_hash($password, PASSWORD_ARGON2ID);
$upd = $pdo->prepare('UPDATE users SET password_hash = :h WHERE id = :id');
$upd->execute([':h' => $newHash, ':id' => $user['id']]);
}
// continue login
}This lets you move users from MD5, SHA1 or an old bcrypt cost to a stronger hash gradually, without forcing everyone to reset their password.
Which database column type should you use?
Use VARCHAR(255). A bcrypt hash is 60 characters today, but the manual recommends 255 because PASSWORD_DEFAULT may produce longer hashes in the future. A column that is too short silently truncates the hash and makes every login fail.
Common password_hash() mistakes
- Using MD5, SHA1 or SHA256 for passwords. They are fast, which is exactly what you do not want for password storage.
- Passing your own salt. Custom salts are ignored since PHP 8.0, and PHP already generates a better one.
- Trimming or changing the password. Hash the exact string the user typed. Do not strip characters or lowercase it.
- Comparing hashes with == or ===. Always use
password_verify(). - Short database columns. Use
VARCHAR(255). - Long passphrases with bcrypt. Bcrypt ignores everything after 72 bytes.
- Logging passwords. Make sure error logs and debug output never contain the plain password.
If you are also setting up your database connection, read our guide on PHP database connection and encrypting passwords.
Hashing vs encryption vs salting: what is the difference?
These three words are often mixed up, and mixing them up leads to unsafe code.
- Encryption is two-way. You encrypt data with a key and can decrypt it later with the same or a related key. It is right for data you must read again, such as an API token, and wrong for passwords.
- Hashing is one-way. You cannot turn the hash back into the password. You can only hash a new attempt and compare. This is what passwords need.
- Salting adds a random value to each password before hashing, so two users with the same password get different hashes and precomputed rainbow tables stop working.
password_hash()does this automatically.
A fast hash such as SHA-256 is a good hash for files, but a bad one for passwords, because an attacker can test billions of guesses per second on a GPU. Password hashing algorithms like bcrypt and Argon2id are intentionally slow and, in the case of Argon2id, memory-hungry, which makes every guess expensive.
A reusable PasswordService class
Instead of repeating hashing code in every file, wrap it in one small class. This keeps your algorithm, options and upgrade logic in a single place, so changing from bcrypt to Argon2id later means editing one file.
<?php
final class PasswordService
{
private const OPTIONS = [
'memory_cost' => 19456, // KiB
'time_cost' => 2,
'threads' => 1,
];
private function algo(): string|int
{
return defined('PASSWORD_ARGON2ID') ? PASSWORD_ARGON2ID : PASSWORD_BCRYPT;
}
private function options(): array
{
return defined('PASSWORD_ARGON2ID') ? self::OPTIONS : ['cost' => 12];
}
public function hash(string $password): string
{
return password_hash($password, $this->algo(), $this->options());
}
public function verify(string $password, string $hash): bool
{
return password_verify($password, $hash);
}
public function needsRehash(string $hash): bool
{
return password_needs_rehash($hash, $this->algo(), $this->options());
}
}Now your registration and login code only calls $service->hash(), $service->verify() and $service->needsRehash(). The class falls back to bcrypt on servers without Argon2, and needsRehash() will quietly move users to Argon2id once you deploy to a server that supports it.
Should you add a pepper?
A pepper is a secret value that is mixed into every password before hashing, and it is stored outside the database, for example in an environment variable or a secrets manager. If an attacker steals only your database, the pepper makes cracking much harder because it is missing from the dump.
<?php
$pepper = getenv('APP_PEPPER'); // never store this in the database
function pepperedHash(string $password, string $pepper): string
{
$prehash = hash_hmac('sha256', $password, $pepper);
return password_hash($prehash, PASSWORD_DEFAULT);
}
function pepperedVerify(string $password, string $hash, string $pepper): bool
{
$prehash = hash_hmac('sha256', $password, $pepper);
return password_verify($prehash, $hash);
}A pepper is optional, and it adds responsibility. If you lose it, nobody can log in, and rotating it needs a careful plan. If you are not ready to manage a secret safely, skip it and get the basics right first. A side benefit of the HMAC pre-hash is that its output is a fixed 64 characters, which also avoids the 72-byte bcrypt limit.
How to migrate old MD5 or SHA1 passwords to password_hash()
If your project still stores MD5 or SHA1 hashes, you do not need to ask every user to reset their password. Upgrade each account the next time its owner logs in:
<?php
function login(PDO $pdo, string $email, string $password): bool
{
$stmt = $pdo->prepare('SELECT id, password_hash, legacy_md5 FROM users WHERE email = :e');
$stmt->execute([':e' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$user) {
return false;
}
// 1. New style hash
if (!empty($user['password_hash'])) {
return password_verify($password, $user['password_hash']);
}
// 2. Old MD5 hash: verify it, then upgrade immediately
if (hash_equals($user['legacy_md5'], md5($password))) {
$new = password_hash($password, PASSWORD_DEFAULT);
$upd = $pdo->prepare('UPDATE users SET password_hash = :h, legacy_md5 = NULL WHERE id = :id');
$upd->execute([':h' => $new, ':id' => $user['id']]);
return true;
}
return false;
}Note the use of hash_equals() for the old comparison, which is timing-safe. For accounts that never log in again, you can also wrap the old hash with a strong one right away: store password_hash($oldMd5Hash, PASSWORD_DEFAULT) and verify with password_verify(md5($password), $hash). This protects the whole table immediately, and you can still upgrade each user on their next login.
Prevent user enumeration and timing leaks
In the basic login example, a request for an unknown email returns faster than a request for a real email, because PHP skips the slow hash check. Attackers can measure this difference and find out which emails are registered. A simple fix is to always run one verification, even when the user does not exist:
<?php
// A valid hash of any random password, created once and stored in config
const DUMMY_HASH = '$2y$12$abcdefghijklmnopqrstuuK0mQK6R6fN9eJ3x1sTz0mY0vYk3b8wS';
$hash = $user['password_hash'] ?? DUMMY_HASH;
$ok = password_verify($password, $hash) && $user !== false;Generate your own dummy hash with password_hash(), since the string above is only an example format. Combine this with a generic error message, rate limiting by IP and by account, and a short lockout or CAPTCHA after repeated failures.
Password reset tokens: do it safely
Hashing the password correctly is only half of the story. Password reset links are a common weak point. Follow these rules:
<?php
$token = bin2hex(random_bytes(32)); // send this in the email link
$tokenHash = hash('sha256', $token); // store only the hash in the database
$expires = (new DateTimeImmutable('+30 minutes'))->format('Y-m-d H:i:s');
$stmt = $pdo->prepare(
'INSERT INTO password_resets (user_id, token_hash, expires_at) VALUES (:u, :t, :e)'
);
$stmt->execute([':u' => $userId, ':t' => $tokenHash, ':e' => $expires]);- Use
random_bytes(), neverrand(),mt_rand()oruniqid(). - Store only a hash of the token, so a database leak does not expose working reset links.
- Make tokens expire quickly and work only once.
- After a password change, invalidate all other sessions and send a notification email.
Password rules that actually help
Modern guidance, including NIST’s digital identity guidelines, favors length over complexity rules. Rules like “must contain one symbol and one number” push people to predictable choices such as Password1!. A better policy is:
- Allow long passphrases, and allow spaces and Unicode characters.
- Set a sensible minimum length and a high maximum (or no maximum if you use Argon2id).
- Reject passwords that appear in known breach lists. The Have I Been Pwned range API works with a k-anonymity method, so you send only the first five characters of a hash and never the full password.
- Offer two-factor authentication, because a strong hash cannot protect a password that a user typed into a phishing page.
password_hash() in Laravel and WordPress
You may not need to call password_hash() yourself. Frameworks wrap it for you, and you should use their helpers so settings stay consistent:
- Laravel: use
Hash::make($password)andHash::check($password, $hash). The driver is set inconfig/hashing.phpand can be bcrypt or Argon2id. - WordPress: use
wp_hash_password()andwp_check_password(). Do not replace them with your own code. - Symfony: the PasswordHasher component with the
autohasher picks a safe algorithm and handles rehashing for you.
How to test your password hashing code
A few quick checks catch most bugs before they reach production:
<?php
$hash = password_hash('correct horse battery staple', PASSWORD_DEFAULT);
var_dump(password_verify('correct horse battery staple', $hash)); // true
var_dump(password_verify('wrong password', $hash)); // false
var_dump(strlen($hash) <= 255); // true, fits VARCHAR(255)
print_r(password_get_info($hash)); // algo and optionspassword_get_info() returns the algorithm name and the options stored in a hash, which is helpful when you audit your user table and want to know how many accounts still use an older cost or algorithm.
Password storage security checklist
- Use
password_hash()withPASSWORD_ARGON2IDorPASSWORD_DEFAULT. - Store hashes in a
VARCHAR(255)column. - Verify with
password_verify()and upgrade withpassword_needs_rehash(). - Use prepared statements for every query.
- Serve the site over HTTPS only and mark session cookies as
Secure,HttpOnlyandSameSite. - Regenerate the session ID after login with
session_regenerate_id(true). - Use a generic login error message and add rate limiting.
- Offer two-factor authentication.
- Keep PHP updated, because security fixes and better defaults arrive with new versions.
Frequently asked questions
Is password_hash() secure enough for production?
Yes. password_hash() generates a random salt, uses a slow adaptive algorithm (bcrypt by default, or Argon2id if you choose it) and stores the algorithm, cost and salt inside the hash string. Used with password_verify() and HTTPS, it is the standard, recommended way to store passwords in PHP.
Should I use bcrypt or Argon2id in PHP?
OWASP lists Argon2id as the first choice for new systems, and PHP supports it through PASSWORD_ARGON2ID when PHP is built with Argon2 support. Bcrypt is still acceptable and is what PASSWORD_DEFAULT uses today. If you are unsure, use PASSWORD_DEFAULT or PASSWORD_ARGON2ID and let password_needs_rehash() upgrade old hashes.
How long should the database column for a password hash be?
Use VARCHAR(255). A bcrypt hash is 60 characters today, but the PHP manual recommends 255 because PASSWORD_DEFAULT can change to an algorithm with longer output in future PHP versions.
Can I decrypt a password_hash() value?
No. password_hash() is a one-way hash, not encryption. You never recover the original password. You only check a login attempt with password_verify(), which hashes the input with the stored salt and cost and compares the result.
Why does password_hash() give a different result every time?
Because PHP generates a new random salt for every call. That is expected and safe. password_verify() reads the salt from the stored hash, so verification still works.
What is the 72-byte limit in bcrypt?
Bcrypt only uses the first 72 bytes of a password and ignores the rest. For most users this is not an issue, but if you allow very long passphrases, consider Argon2id or enforce a maximum length of 72 bytes.
Conclusion
For almost every PHP project, the safe recipe is simple: hash with password_hash(), store in VARCHAR(255), verify with password_verify() and upgrade with password_needs_rehash(). Pick Argon2id when it is available, keep bcrypt as a fallback, and keep your cost settings under review as hardware gets faster.



