PHP password_hash and password_verify are the only two functions most applications need to store passwords safely. They pick a slow, salted algorithm, generate a random salt, store the algorithm and cost inside the hash, and compare in a way that resists timing attacks. Yet login code in the wild still uses md5(), hand-made salts, or a correct password_hash() call stored in a column too short for future hashes. This guide covers what the hash string contains, bcrypt versus Argon2id, choosing a cost on your own server, a complete PDO login flow that upgrades hashes automatically, the 72-byte bcrypt limit, and how to migrate an old MD5 user table without forcing everyone to reset their password. Every example was run on PHP 8.5.

PHP password_hash workflow: hash with PASSWORD_DEFAULT on registration, password_verify on login, password_needs_rehash to upgrade old bcrypt or MD5 hashes
PHP password hashing options: bcrypt through PASSWORD_DEFAULT, Argon2id where available, and legacy MD5 or SHA hashes that should be migrated.

From my own work: When I take over older PHP projects, the password code is often the riskiest part: unsalted MD5 in a custom user table, or a correct password_hash() call stored in a VARCHAR(60) column. The migration below is the one I use, because it upgrades every account at once without a mass password reset email.

PHP password_hash and password_verify in two lines

Hash when the user registers or changes their password, and verify when they log in. You never decrypt a password hash; you hash the attempt and let PHP compare (PHP manual: password_hash(), PHP manual: password_verify()):

<?php
$hash = password_hash($password, PASSWORD_DEFAULT);   // store this string

if (password_verify($attempt, $hash)) {
    // correct password
}

Do not add your own salt and do not hash the password with md5() or sha256 first. password_hash() generates a cryptographically random salt for every call, so hashing the same password twice gives two different strings, and both verify.

What the hash string contains

A bcrypt hash produced by PHP 8.5 looks like this:

$2y$12$9ut1DVvz0QybHJ9NbPWAjeLMcwtCVhc8OomNP1BDQwW56jCoNZ8Mq
 |  |  |                      |
 |  |  salt (22 chars)        hash (31 chars)
 |  cost 12 = 2^12 rounds
 algorithm 2y = bcrypt

Because the algorithm, cost and salt are inside the string, password_verify() needs nothing else, and you can change settings later without breaking existing hashes. password_get_info() decodes the parts:

php -r 'print_r(password_get_info(password_hash("x", PASSWORD_DEFAULT)));'
# Array ( [algo] => 2y [algoName] => bcrypt [options] => Array ( [cost] => 12 ) )

Store hashes in a VARCHAR(255) column. A bcrypt hash is 60 characters today, but PASSWORD_DEFAULT is designed to change to stronger algorithms over time and the PHP manual recommends a column that can grow well beyond 60 characters, with 255 as a good choice (PHP manual: algorithm constants). An Argon2id hash is already about 97 characters.

bcrypt vs Argon2id: which algorithm to use

Algorithm PHP constant PHP 8.5 defaults Notes
bcrypt PASSWORD_DEFAULT, PASSWORD_BCRYPT cost 12 Available everywhere; inputs over 72 bytes are truncated
Argon2id PASSWORD_ARGON2ID memory 65536 KiB, time 4, threads 1 Memory-hard; only if PHP was built with Argon2 support
Argon2i PASSWORD_ARGON2I Same as above Prefer Argon2id for password storage
MD5, SHA-1, SHA-256 None (general hashes) Not applicable Too fast; billions of guesses per second on GPUs

The default bcrypt cost was raised from 10 to 12 in PHP 8.4 (see the changelog on the password_hash() manual page). The OWASP Password Storage Cheat Sheet recommends Argon2id with at least 19 MiB of memory, two iterations and one degree of parallelism, and accepts bcrypt with a work factor of 10 or more where Argon2id is not available (OWASP Password Storage Cheat Sheet). PHP’s Argon2id defaults are above that minimum.

Check what your PHP build supports before choosing Argon2id, because shared hosting and some distributions compile PHP without it:

php -r 'var_dump(password_algos(), defined("PASSWORD_ARGON2ID"));'
# array(3) { [0]=> string(2) "2y" [1]=> string(7) "argon2i" [2]=> string(8) "argon2id" }
# bool(true)

In practice, PASSWORD_DEFAULT (bcrypt, cost 12) is a sound choice for most PHP applications. Choose Argon2id if every server that will verify hashes supports it and you have measured the memory cost under peak login traffic: each concurrent login with the defaults uses 64 MiB of memory while it hashes.

Benchmark the cost on your own server

A higher cost makes each guess slower for an attacker and each login slower for you. Measure on the production server, not on a laptop, because CPU speed differs widely:

<?php
// cost.php - run on the production server, not your laptop
$target = (float) ($argv[1] ?? 0.25);   // seconds per hash you can afford at peak login rate
for ($cost = 10; $cost <= 16; $cost++) {
    $start = hrtime(true);
    password_hash('benchmark-password', PASSWORD_BCRYPT, ['cost' => $cost]);
    $sec = (hrtime(true) - $start) / 1e9;
    printf("cost %2d: %6.0f msn", $cost, $sec * 1000);
    if ($sec > $target) break;
}
if (defined('PASSWORD_ARGON2ID')) {
    $start = hrtime(true);
    password_hash('benchmark-password', PASSWORD_ARGON2ID);   // m=64 MiB, t=4, p=1 defaults
    printf("argon2id defaults: %.0f msn", (hrtime(true) - $start) / 1e6);
}

Run it with php cost.php 0.25. Each step of the bcrypt cost roughly doubles the time. Pick the highest cost that stays within your budget, and remember that login floods multiply it: a server that can afford 250 ms per hash can process only a few logins per second per CPU core. Rate limiting the login endpoint matters as much as the cost; for WordPress, see Nginx rate limiting for WordPress and wp-config.php security hardening.

A complete login flow with password_needs_rehash

password_needs_rehash() returns true when a stored hash was made with a different algorithm or options than the ones you pass now (PHP manual: password_needs_rehash()). Calling it after a successful login is how you upgrade every active account to a new cost or algorithm, using the plain password you briefly have in memory. This file works with any PDO driver:

<?php
// auth.php - PHP 8.1+; works with MySQL, MariaDB, PostgreSQL or SQLite via PDO
declare(strict_types=1);

const HASH_ALGO    = PASSWORD_DEFAULT;          // bcrypt today, upgrades with PHP
const HASH_OPTIONS = [];                         // or ['cost' => 13] after benchmarking

function register_user(PDO $db, string $email, string $password): int
{
    if (strlen($password) < 12) {
        throw new InvalidArgumentException('Password must be at least 12 characters');
    }
    if (strlen($password) > 72 && HASH_ALGO === PASSWORD_BCRYPT) {
        throw new InvalidArgumentException('Password is longer than 72 bytes');
    }
    $hash = password_hash($password, HASH_ALGO, HASH_OPTIONS);
    $stmt = $db->prepare('INSERT INTO users (email, password_hash) VALUES (?, ?)');
    $stmt->execute([strtolower($email), $hash]);
    return (int) $db->lastInsertId();
}

function login(PDO $db, string $email, string $password): ?array
{
    $stmt = $db->prepare('SELECT id, email, password_hash FROM users WHERE email = ?');
    $stmt->execute([strtolower($email)]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    // Verify against a dummy hash when the user does not exist, so response
    // time does not reveal which email addresses are registered.
    $hash = $user['password_hash'] ?? '$2y$12$sOlQ/uDAgulthL05sDt2FuuFrzNHS8KJC9lOWW7HjUuhNzvYdmyl.';
    if (!password_verify($password, $hash) || $user === false) {
        return null;
    }

    // Upgrade the stored hash when the algorithm or cost has changed.
    if (password_needs_rehash($user['password_hash'], HASH_ALGO, HASH_OPTIONS)) {
        $new = password_hash($password, HASH_ALGO, HASH_OPTIONS);
        $db->prepare('UPDATE users SET password_hash = ? WHERE id = ?')->execute([$new, $user['id']]);
    }
    unset($user['password_hash']);
    return $user;
}

The test below uses an in-memory SQLite database, registers a user, tries good and bad passwords, then replaces the hash with an old cost-10 hash and confirms the next login upgrades it:

<?php
require __DIR__ . '/auth.php';
$db = new PDO('sqlite::memory:', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$db->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, email VARCHAR(255) UNIQUE NOT NULL, password_hash VARCHAR(255) NOT NULL)');

$id = register_user($db, 'Rahim@example.com', 'correct horse battery staple');
var_dump(login($db, 'rahim@example.com', 'correct horse battery staple'));   // array with id and email
var_dump(login($db, 'rahim@example.com', 'wrong password'));                 // NULL
var_dump(login($db, 'nobody@example.com', 'whatever'));                      // NULL

$db->prepare('UPDATE users SET password_hash = ? WHERE id = ?')
   ->execute([password_hash('correct horse battery staple', PASSWORD_BCRYPT, ['cost' => 10]), $id]);
echo substr($db->query('SELECT password_hash FROM users')->fetchColumn(), 0, 7), "n";   // $2y$10$
login($db, 'rahim@example.com', 'correct horse battery staple');
echo substr($db->query('SELECT password_hash FROM users')->fetchColumn(), 0, 7), "n";   // $2y$12$

Two details in login() are deliberate. The dummy hash, generated once with password_hash(), makes a login for an unknown email take as long as one for a real account; in the test both took about the same time, so an attacker cannot use response time to discover which addresses are registered. And the error message for the user should be the same in both cases, such as Incorrect email or password.

The 72-byte bcrypt limit and NUL bytes

bcrypt only uses the first 72 bytes of its input. PHP does not warn you; it silently ignores the rest, so two long passwords that share the first 72 bytes verify against each other:

<?php
$long = str_repeat('a', 72);
$h = password_hash($long . 'X', PASSWORD_BCRYPT);
var_dump(password_verify($long . 'Y', $h));    // bool(true)  - the 73rd byte is ignored

password_hash("abcd", PASSWORD_BCRYPT);
// ValueError: Bcrypt password must not contain null character

72 bytes is fewer characters than it sounds for non-Latin scripts: a Bangla character takes three bytes in UTF-8, so a Bangla passphrase can reach the limit at 24 characters. You have three options: reject longer passwords, as register_user() does for bcrypt; switch to Argon2id, which has no such limit; or pre-hash with a keyed hash and encode the result so it contains no NUL bytes:

<?php
// prehash.php - allow passwords longer than 72 bytes with bcrypt
// HMAC-SHA384 -> 48 raw bytes -> 64 base64 characters, no NUL bytes, under the limit
const PEPPER_CONTEXT = 'myapp-password-v1';

function prehash(string $password): string
{
    return base64_encode(hash_hmac('sha384', $password, PEPPER_CONTEXT, true));
}

$long = str_repeat('a', 72);
$h = password_hash(prehash($long . 'X'), PASSWORD_BCRYPT);
var_dump(password_verify(prehash($long . 'X'), $h));   // true
var_dump(password_verify(prehash($long . 'Y'), $h));   // false: the 73rd byte now matters

If you pre-hash, apply it consistently everywhere you hash and verify, and mark such hashes so you can tell them apart. WordPress 6.8 took this route: it switched to bcrypt, pre-hashes with SHA-384 to avoid the 72-byte limit and stores those hashes with a $wp prefix so they are distinguishable from plain bcrypt hashes (Make WordPress Core: bcrypt in 6.8).

Migrate MD5 or SHA1 password hashes without a reset

Waiting for every user to log in can take years, and the old hashes stay exposed in every backup until then. A better approach upgrades the whole table immediately: wrap each existing MD5 hash in bcrypt, then replace the wrapped hash with a normal one at the next login:

<?php
// legacy.php - move unsalted MD5 hashes to bcrypt without waiting for logins
// Step 1 (one-off migration): wrap every old hash
function wrap_legacy(string $md5hex): string
{
    return 'legacy$' . password_hash($md5hex, PASSWORD_DEFAULT);
}

// Step 2 (at login): verify either format, then store a normal hash
function verify_and_upgrade(string $password, string $stored, callable $save): bool
{
    if (str_starts_with($stored, 'legacy$')) {
        $ok = password_verify(md5($password), substr($stored, 7));
    } else {
        $ok = password_verify($password, $stored);
    }
    if ($ok && (str_starts_with($stored, 'legacy$') || password_needs_rehash($stored, PASSWORD_DEFAULT))) {
        $save(password_hash($password, PASSWORD_DEFAULT));
    }
    return $ok;
}

$stored = wrap_legacy(md5('old-password-123'));       // what the migration writes
$ok = verify_and_upgrade('old-password-123', $stored, function ($h) use (&$stored) { $stored = $h; });
var_dump($ok, substr($stored, 0, 7));                  // bool(true) string(7) "$2y$12$"
var_dump(verify_and_upgrade('wrong', $stored, fn ($h) => null));   // bool(false)

Run step 1 as a batch job over the user table, then delete or securely overwrite old database dumps that still contain the raw MD5 values. The same pattern works for sha1() or salted legacy schemes: wrap the old hash value, and reproduce the old calculation inside verify_and_upgrade().

Common mistakes to avoid

  • Comparing hashes with ==. Always use password_verify(); for other secrets such as API tokens, use hash_equals().
  • A VARCHAR(60) column. It truncates Argon2id hashes and future defaults. Use 255.
  • Trimming or changing the password. Hash exactly what the user typed. If you normalise input, do it identically at registration and login.
  • Logging passwords. Debug logs, exception traces and request dumps often capture POST bodies. Filter password fields before logging.
  • No rate limiting. Even a strong hash cannot stop an attacker trying common passwords against thousands of accounts online.
  • Old PHP versions. Upgrade to a supported release to get current defaults and security fixes; upgrading the PHP version on Ubuntu shows how for WordPress servers.

If an old database has already leaked, rotating hashes is not enough: force password resets for affected accounts and check for other compromise, as in cleaning a hacked WordPress site. For new applications, passkeys remove shared secrets altogether; an implementation is covered in WebAuthn passkeys authentication.

PHP password_hash checklist

  • password_hash($pw, PASSWORD_DEFAULT) on registration and password change.
  • password_verify() on login; never == or md5().
  • password_needs_rehash() after every successful login.
  • VARCHAR(255) column for hashes.
  • Cost benchmarked on the production server; login rate limited.
  • 72-byte limit handled: reject, use Argon2id, or pre-hash consistently.
  • Dummy hash for unknown users and one generic error message.
  • Legacy MD5 or SHA1 hashes wrapped immediately, upgraded at login.

Want this done on your own server or site?

I am Saizul Amin, a web developer and technical SEO consultant. I set up and harden VPS servers, migrate WordPress sites, fix indexing problems and build automations. See my portfolio or get in touch.

FAQ

Is PHP password_hash secure?

Yes, when used with PASSWORD_DEFAULT or PASSWORD_ARGON2ID. It uses a slow, salted algorithm with a random salt for every hash and stores the settings inside the hash. Pair it with password_verify(), a VARCHAR(255) column and rate limiting on the login form.

Should I use bcrypt or Argon2id in PHP?

Both are acceptable. bcrypt through PASSWORD_DEFAULT works on every PHP build and is a sound default. Argon2id is memory-hard and recommended by OWASP, but only use it if every server that verifies hashes was built with Argon2 support and you have measured its memory use.

What is the default bcrypt cost in PHP 8.4 and 8.5?

The default cost is 12. It was raised from 10 to 12 in PHP 8.4. Existing hashes with cost 10 keep working, and password_needs_rehash() returns true for them so you can upgrade them at the next login.

Can I decrypt a password_hash value?

No. A password hash is one-way. To check a password you hash the login attempt with the same salt and settings, which password_verify() does for you. If a user forgets their password, send a reset link instead of trying to recover it.

How do I migrate MD5 passwords to password_hash?

Wrap each stored MD5 hash with password_hash() in a one-off migration and mark it as legacy. At login, verify by hashing the attempt with md5() and checking it against the wrapped hash, then replace it with a normal password_hash() of the plain password.

Sources

NEW BLOGS. REAL STRATEGIES. REAL RESULTS.

Join our community and receive powerful SEO tips, web optimization guides, and growth strategies as soon as they’re published.

Don’t just read blogs — stay ahead of the competition.

We don’t spam! Read our privacy policy for more info.

Share.

Comments are closed.