Use password_hash($password, PASSWORD_DEFAULT) when the user signs up and store the 60-character result, then check a login with password_verify($input, $hash). PHP generates the salt and stores it inside the hash, together with the algorithm (bcrypt, $2y$) and the cost (12 on PHP 8.4 and later). Never use md5, sha1 or hash('sha256') for passwords, with or without a salt.
A password hash has to be slow, salted and one-way, and PHP has had a built-in API for that since PHP 5.5: password_hash, password_verify and password_needs_rehash. They replace the hand-rolled crypt() and salt code you still find in old answers. The sections below cover hashing and checking, upgrading old hashes when a user logs in, choosing a cost for your server, Argon2id, bcrypt's 72-byte input limit, and why fast hashes such as SHA-256 are the wrong tool, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1password_hash and password_verifyRecommended
At sign-up, call password_hash with PASSWORD_DEFAULT and save the string it returns. At login, load that string and pass it to password_verify along with what the user typed; it returns true or false. You never handle a salt: PHP makes a random one for every call and writes it into the hash, so the database needs one column, not two. Store it in a VARCHAR(255) column, as the PHP manual recommends, because PASSWORD_DEFAULT may move to a longer algorithm in a later release.
<?php // Sign-up: hash the password and store the string (VARCHAR(255) column) $password = 'correct horse battery staple'; $hash = password_hash($password, PASSWORD_DEFAULT); echo 'Prefix: ', substr($hash, 0, 7), "\n"; echo 'Length: ', strlen($hash), "\n"; // $2y$ = bcrypt, then the cost, then 22 chars of salt and 31 of hash preg_match('~^\$2y\$(\d{2})\$(.{22})(.{31})$~', $hash, $m); echo "cost {$m[1]}, salt ", strlen($m[2]), ' chars, hash ', strlen($m[3]), " chars\n"; // Log-in: check what the user typed against the stored hash var_dump(password_verify('correct horse battery staple', $hash)); var_dump(password_verify('Correct horse battery staple', $hash)); // The same password gives a different hash every time (new random salt) $again = password_hash($password, PASSWORD_DEFAULT); var_dump($hash === $again); var_dump(password_verify($password, $again)); // Everything password_verify needs is inside the string print_r(password_get_info($hash));
Output
The hash starts with $2y$12$ and is 60 characters long: $2y$ means bcrypt, 12 is the cost, then come 22 characters of salt and 31 of hash (cost 12, salt 22 chars, hash 31 chars). The correct password verifies and the one with a capital C does not. Hashing the same password twice gives two different strings ($hash === $again is false), yet both verify, because password_verify reads the salt and cost back out of the stored hash. That is also why you must never compare hashes with === or look a user up by hash. password_get_info shows the same facts: [algoName] => bcrypt, [cost] => 12. PHP 8.4 raised the default cost from 10 to 12.
2Upgrade old hashes with password_needs_rehash
Hashes made with an older cost or algorithm stay valid, but they are weaker than new ones. You can't upgrade them in bulk, because you don't have the passwords. The moment you do have one is a successful login: after password_verify returns true, ask password_needs_rehash whether the stored hash matches your current settings, and if not, hash the password again and save it. Pass it the same algorithm and options you give password_hash.
<?php // A user row saved years ago, when the app used cost 10 $users = [ '[email protected]' => password_hash('hunter2', PASSWORD_BCRYPT, ['cost' => 10]), ]; function login(array &$users, string $email, string $password): bool { $stored = $users[$email] ?? null; if ($stored === null || !password_verify($password, $stored)) { return false; } // The password is correct and in hand: upgrade the hash if it is old if (password_needs_rehash($stored, PASSWORD_DEFAULT)) { $users[$email] = password_hash($password, PASSWORD_DEFAULT); echo " (hash upgraded)\n"; // in an app: UPDATE users SET ... } return true; } echo 'Before: ', substr($users['[email protected]'], 0, 7), "\n"; var_dump(login($users, '[email protected]', 'wrong')); var_dump(login($users, '[email protected]', 'hunter2')); echo 'After: ', substr($users['[email protected]'], 0, 7), "\n"; var_dump(login($users, '[email protected]', 'hunter2')); // A change of algorithm is picked up the same way $current = $users['[email protected]']; var_dump(password_needs_rehash($current, PASSWORD_ARGON2ID));
Output
The stored hash starts as $2y$10$, the default before PHP 8.4. A wrong password returns false and changes nothing. The right one prints (hash upgraded), and the row now holds a $2y$12$ hash; the next login finds nothing to do. The last line, bool(true), shows that switching the algorithm to Argon2id would trigger the same upgrade, so this one check covers both cost and algorithm changes. Users who never log in again keep their old hash, which is fine as long as the old setting was a slow password hash.
3Choosing the bcrypt cost
The cost is a power of two: each step up doubles the work, for you and for anyone trying to guess passwords from a stolen database. The default of 12 suits most servers, but the right value is the highest one your login can afford, so measure it on the machine that runs your app. A common target is somewhere between 100 and 500 ms per hash. The loop below times costs 10 to 12 with hrtime and keeps the slowest that fits a 300 ms budget. The timings differ from run to run, so expect slightly different numbers each time you press Run.
<?php // Time one hash per cost on this server and keep the slowest that fits $targetMs = 300; $chosen = 10; foreach ([10, 11, 12] as $cost) { $start = hrtime(true); password_hash('benchmark', PASSWORD_BCRYPT, ['cost' => $cost]); $ms = (hrtime(true) - $start) / 1e6; printf("cost %d: %d ms\n", $cost, $ms); if ($ms <= $targetMs) { $chosen = $cost; } } echo "Highest cost under {$targetMs} ms: {$chosen}\n"; // Then pass it as an option; verify reads it back from the hash $hash = password_hash('hunter2', PASSWORD_DEFAULT, ['cost' => $chosen]); echo substr($hash, 0, 7), "\n"; var_dump(password_verify('hunter2', $hash));
Output
One run on this page printed cost 10: 58 ms, cost 11: 117 ms and cost 12: 234 ms: each step doubles the time, so cost 12 fits the 300 ms budget and cost 13 would not. Pass the chosen value as ['cost' => $chosen]; the hash then starts with that cost, and password_verify needs no options because it reads the cost from the hash. Bcrypt accepts costs from 4 to 31; outside that range password_hash throws ValueError: Invalid bcrypt cost parameter specified: 3. Every login pays this time once, so a cost that takes seconds also makes your login page easy to overload.
4Argon2id with PASSWORD_ARGON2ID
Argon2id is the newer password hash, available as PASSWORD_ARGON2ID since PHP 7.3 when PHP is built with Argon2 support (check with defined('PASSWORD_ARGON2ID')). Besides time it costs memory, which makes guessing on GPUs and custom hardware much more expensive than with bcrypt. It takes three options: memory_cost in KiB, time_cost (passes over that memory) and threads. The values below, 19 MiB, 2 passes and 1 thread, are the minimum the OWASP password storage guidance gives for Argon2id.
<?php if (!defined('PASSWORD_ARGON2ID')) { exit("This PHP build has no Argon2 support\n"); } // Memory in KiB, passes over that memory, and parallel lanes $options = ['memory_cost' => 19456, 'time_cost' => 2, 'threads' => 1]; $hash = password_hash('hunter2', PASSWORD_ARGON2ID, $options); // The parameters are stored in the hash, ahead of the salt $parts = explode('$', $hash); echo '$', $parts[1], '$', $parts[2], '$', $parts[3], "\n"; echo 'Length: ', strlen($hash), "\n"; var_dump(password_verify('hunter2', $hash)); var_dump(password_verify('hunter3', $hash)); // PHP's defaults, used when you pass no options echo PASSWORD_ARGON2_DEFAULT_MEMORY_COST, ' KiB, ', PASSWORD_ARGON2_DEFAULT_TIME_COST, ' passes, ', PASSWORD_ARGON2_DEFAULT_THREADS, " thread\n"; // password_verify also accepts bcrypt hashes, so you can mix them $old = password_hash('hunter2', PASSWORD_BCRYPT); var_dump(password_verify('hunter2', $old)); var_dump(password_needs_rehash($old, PASSWORD_ARGON2ID, $options));
Output
The hash begins with $argon2id$v=19$m=19456,t=2,p=1: the algorithm, its version and your three options, followed by the salt and the hash, 97 characters in all. Without options PHP uses 65536 KiB, 4 passes, 1 thread. Memory is reserved per hash, so 64 MiB times the number of logins at once is real RAM; pick values your server can carry, and too little memory throws ValueError: Memory cost is outside of allowed memory range. The last two lines show a bcrypt hash still verifying while password_needs_rehash reports true, so you can move an existing site to Argon2id with the login upgrade from section 2. Pick Argon2id when your build has it and you want the stronger hash or longer passwords; bcrypt with PASSWORD_DEFAULT remains a sound, portable choice.
5The 72-byte bcrypt limit
Bcrypt uses only the first 72 bytes of the password. PHP 8.5 does not warn about longer input; it ignores the rest, so two long passwords that share their first 72 bytes verify against each other. The limit is in bytes, not characters, which matters for passphrases with accented letters or emoji. You have three ways out: cap passwords at 72 bytes in your form, use Argon2id, or pre-hash the password into a short string before bcrypt.
<?php $long = str_repeat('a', 72); $hash = password_hash($long . 'SECRET', PASSWORD_BCRYPT); // bcrypt reads only the first 72 bytes: a different ending still matches var_dump(password_verify($long . 'wrong', $hash)); // Bytes, not characters: 40 x "é" is already 80 bytes in UTF-8 $accents = str_repeat('é', 40); echo strlen($accents), ' bytes, ', mb_strlen($accents), " characters\n"; // Option 1: Argon2id has no 72-byte limit $argon = password_hash($long . 'SECRET', PASSWORD_ARGON2ID); var_dump(password_verify($long . 'wrong', $argon)); // Option 2: pre-hash to 64 printable characters, then bcrypt that function prehash(string $password): string { // base64, not raw binary: bcrypt rejects a NUL byte return base64_encode(hash('sha384', $password, true)); } echo strlen(prehash($long . 'SECRET')), "\n"; $hash = password_hash(prehash($long . 'SECRET'), PASSWORD_BCRYPT); var_dump(password_verify(prehash($long . 'SECRET'), $hash)); var_dump(password_verify(prehash($long . 'wrong'), $hash));
Output
The first bool(true) is the problem: a password ending in wrong matches one ending in SECRET, because both start with the same 72 bytes. Forty é characters are already 80 bytes. Argon2id compares the whole input and returns bool(false). The pre-hash turns any password into 64 base64 characters, so bcrypt sees all of it. Use base64 or hex, never the raw binary digest: binary output can contain a NUL byte, and on PHP 8.5 password_hash then throws ValueError: Bcrypt password must not contain null character. Apply the same pre-hash in password_verify, and note that existing plain bcrypt hashes won't match it, so switch only for new hashes or new users.
6Why not md5, sha1 or sha256 with a salt
The old advice was md5($salt . $password) or hash('sha256', $salt . $password). A salt stops precomputed tables and makes equal passwords hash differently, but it does nothing about speed, and speed is what an attacker with your database needs: these hashes are built to be fast, so guessing millions of passwords costs almost nothing. The script times one bcrypt hash, then counts how many salted SHA-256 hashes fit in the same time. The second half shows hash_equals, the comparison to use for secrets you check yourself, such as API tokens or HMAC signatures.
<?php // How many salted sha256 guesses fit in the time of one bcrypt hash? $start = hrtime(true); password_hash('hunter2', PASSWORD_DEFAULT); $bcryptNs = hrtime(true) - $start; $count = 0; $start = hrtime(true); while (hrtime(true) - $start < $bcryptNs) { hash('sha256', 'per-user-salt' . 'guess' . $count); $count++; } printf("1 bcrypt hash: %d ms\n", $bcryptNs / 1e6); printf("sha256 hashes in the same time: %s\n", number_format($count)); // For secrets you compare yourself (API tokens, signatures), use // hash_equals: its run time does not depend on where the strings differ $key = 'server-side-key'; $expected = hash_hmac('sha256', 'order=1001&amount=25.00', $key); $fromRequest = $expected; // e.g. read from a header var_dump(hash_equals($expected, $fromRequest)); var_dump(hash_equals($expected, str_repeat('0', 64)));
Output
One run printed 1 bcrypt hash: 235 ms and sha256 hashes in the same time: 396,178: about 400,000 guesses against a salted SHA-256 hash for every single guess against bcrypt, on one CPU core, in PHP. Dedicated cracking tools on GPUs are far faster than that, and md5 is faster still. For a token or signature, compare with hash_equals($expected, $fromRequest), known value first: it returns true for the match and false for the forged value, and its run time does not reveal how many leading characters were right, which === can. You don't need it for passwords, because password_verify already compares safely.
7Which should you use?
| Method | Safe for passwords | Notes | Best for |
|---|---|---|---|
| password_hash($pw, PASSWORD_DEFAULT) | Yes | bcrypt, cost 12, 60 chars | Most apps: the default choice |
| password_hash($pw, PASSWORD_ARGON2ID) | Yes | Memory-hard, no 72-byte limit | New apps where the build has Argon2 |
| password_needs_rehash | Companion | Run after a successful verify | Raising the cost or changing algorithm |
| crypt($pw, '$2y$...') | Yes, if salted right | You build the salt yourself | Old code; password_verify reads it |
| hash_equals($known, $input) | Not a hash | Timing-safe string compare | API tokens, HMAC signatures |
| md5 / sha1 / sha256 + salt | No | Hundreds of thousands per bcrypt | Checksums, never passwords |
Frequently asked questions
What is the difference between PASSWORD_DEFAULT and PASSWORD_BCRYPT?
Today both mean bcrypt: on PHP 8.5 PASSWORD_DEFAULT and PASSWORD_BCRYPT are both the string 2y. PASSWORD_BCRYPT always means bcrypt, while PASSWORD_DEFAULT follows whatever PHP considers the best algorithm and may change in a future release. Use PASSWORD_DEFAULT, store hashes in a VARCHAR(255) column, and let password_needs_rehash upgrade old ones on login.
Do I need to generate a salt for password_hash?
No. password_hash creates a random salt for every call and stores it inside the hash, and password_verify reads it back. The salt option was deprecated in PHP 7.0 and is ignored since PHP 8.0; on PHP 8.5 passing it prints Warning: password_hash(): The "salt" option has been ignored, since providing a custom salt is no longer supported.
How long is a password_hash result, and what column type should I use?
A bcrypt hash is always 60 characters ($2y$12$ plus 53). An Argon2id hash with memory_cost 19456, time_cost 2 and threads 1 is 97 characters, and other options change the length. The PHP manual recommends a VARCHAR(255) column so a future PASSWORD_DEFAULT still fits.
Why does password_hash use cost 12 now instead of 10?
PHP 8.4 raised the default bcrypt cost from 10 to 12, so every hash takes about four times as long as before. Hashes made at cost 10 keep working with password_verify; call password_needs_rehash($hash, PASSWORD_DEFAULT) after a successful login to replace them with cost 12 hashes.
Can I decrypt a password hash or get the password back?
No. A password hash is one-way: there is no key and no decrypt function. password_verify hashes the typed password again with the salt and cost stored in the hash and compares the results. If a user forgets the password, send a reset link and let them set a new one.
How did people use bcrypt in PHP before password_hash?
With crypt($password, '$2y$10$' . $salt), where you had to build a 22-character salt from the bcrypt alphabet yourself. password_hash (PHP 5.5) wraps the same bcrypt and handles the salt for you. Hashes made with crypt in the $2y$ format still work with password_verify, so you can switch without resetting passwords.