Web & Development

PHP Password Hashing: Argon2id, bcrypt and Secure Migration

PHP Password Hashing: Argon2id, bcrypt and Secure Migration

Learn how to securely hash passwords in PHP using Argon2id and bcrypt, choose safe parameters, verify credentials and migrate existing hashes without forcing password resets.

Password storage is one of the most important security decisions in a web application. A database breach should not immediately reveal users' credentials, but weak password hashing can make stolen hashes inexpensive to attack.

PHP includes built-in functions for hashing, verifying and upgrading passwords. The challenge is selecting the right algorithm, configuring it for your infrastructure and migrating existing accounts without disrupting authentication.

For new applications, Argon2id is generally the preferred choice when your PHP build supports it. bcrypt remains a practical compatibility option. Both should be used through PHP's password API, rather than through homemade cryptography.

This guide covers implementation, parameter selection, legacy migration and common mistakes.

Why SHA-256 is not suitable for password storage

SHA-256 is designed to be fast. That makes it useful for integrity checks but unsuitable on its own for password storage: an attacker with stolen hashes can test many password guesses quickly.

Dedicated password hashing algorithms deliberately consume more resources. Argon2id can require substantial memory as well as processing time, making large-scale guessing more expensive.

A secure storage system needs a unique random salt, a configurable work factor and a way to increase the work factor as hardware improves. PHP's password_hash() generates and stores the necessary salt information automatically.

The OWASP Password Storage Cheat Sheet recommends adaptive password hashing rather than fast general-purpose hash functions.

Argon2id vs bcrypt: which should you choose?

Feature Argon2id bcrypt
Main defense Memory and computation cost Computation cost
Memory-hard Yes No
Configurable parameters Memory, iterations, parallelism Cost factor
Password input limit No bcrypt-style 72-byte limit 72 bytes
Availability in PHP Depends on build Broadly available
Best fit Preferred for new password storage Compatibility and legacy systems

Argon2id is designed to resist attacks that benefit from massively parallel hardware. bcrypt is still a legitimate adaptive password hashing algorithm, but its input limit requires care: it considers at most the first 72 bytes, not characters.

Do not assume PASSWORD_DEFAULT selects Argon2id. The PHP password_hash documentation currently documents bcrypt as its default algorithm. PHP 8.4 raised bcrypt's default cost from 10 to 12, illustrating why relying on implicit parameters can change application performance after upgrades.

Step 1: Check Argon2id support

Argon2id is not necessarily available on every hosting environment. Check the runtime before selecting it:

<?php
declare(strict_types=1);

if(in_array('argon2id', password_algos(), true)) {
    echo 'Argon2id is available';
} else {
    echo 'Argon2id is not available';
}

Availability depends on how PHP was built. Do not assume that upgrading the PHP version automatically enables Argon2id.

Step 2: Hash a password with Argon2id

OWASP documents several acceptable baseline configurations. One uses 19 MiB of memory, two iterations and parallelism of one. PHP expresses memory_cost in KiB, so 19 MiB is 19 * 1024 KiB.

<?php
declare(strict_types=1);

$options = [
    'memory_cost' => 19 * 1024,
    'time_cost' => 2
];

$password = 'example-user-password';

$hash = password_hash(
    $password,
    PASSWORD_ARGON2ID,
    $options
);

The parallelism option threads is supported with some Argon2 backends, including libargon2, but not every PHP build. If supported, a value of one matches this baseline; omitting it is more portable. Benchmark your actual configuration.

The resulting encoded hash includes the algorithm identifier, parameters and salt. There is no need to save those values in separate database columns. A VARCHAR(255) column is a reasonable starting point for modern password hashes, provided it stores the entire encoded value.

These are baseline parameters, not a universal production configuration. Test latency and memory usage under realistic concurrent authentication traffic.

Step 3: Verify credentials correctly

Illustration of the article's main concept

Because each password hash uses a random salt, generating a new hash and comparing strings will not work. Use password_verify():

<?php
declare(strict_types=1);

$submittedPassword = (string)($_POST['password'] ?? '');
$storedHash = (string)$user['password_hash'];

if(!password_verify($submittedPassword, $storedHash)) {
    // Reject authentication without disclosing account existence.
    return;
}

// The password is valid. Continue with secure session handling.

The PHP documentation specifies that password_verify() is safe against timing attacks. It reads the algorithm and work parameters from the stored hash.

Password verification does not replace login throttling, secure sessions, HTTPS, appropriate error handling or multifactor authentication.

Step 4: Upgrade existing password hashes during login

password_needs_rehash() detects when a stored hash uses an outdated algorithm or parameters. This enables gradual migration without forcing every active user to reset their password.

<?php
declare(strict_types=1);

$options = [
    'memory_cost' => 19 * 1024,
    'time_cost' => 2
];

if(password_verify($submittedPassword, $storedHash)) {
    if(password_needs_rehash(
        $storedHash,
        PASSWORD_ARGON2ID,
        $options
    )) {
        $newHash = password_hash(
            $submittedPassword,
            PASSWORD_ARGON2ID,
            $options
        );

        // Persist with a prepared statement.
        // Prefer a conditional UPDATE to avoid overwriting
        // a newer hash from a concurrent request.
    }

    // Finish authentication and rotate the session identifier.
}

Only rehash after successfully verifying the submitted password. A conditional update can ensure the stored hash still matches the value that was just verified. For example, update the password hash only where both the user ID and old hash match.

See PHP password_needs_rehash() for API details.

Step 5: Migrate legacy MD5 or SHA-1 hashes

Older applications may contain MD5, SHA-1 or custom password formats. Such hashes cannot always be verified with password_verify().

A migration should follow a controlled sequence:

  1. Identify the legacy format using trusted metadata or an unambiguous, documented format.
  2. Verify the submitted password using the original legacy scheme only for accounts that still require it.
  3. After successful verification, immediately create a modern hash using password_hash().
  4. Replace the stored legacy hash using a safe database update.
  5. Retire legacy verification when migration is complete.

Do not guess the algorithm solely from hash length when multiple formats are possible. Do not attempt to decrypt password hashes: hashing is not encryption.

For accounts that never log in, consider a password reset policy rather than retaining weak hashes indefinitely. Do not introduce an insecure fallback path that accepts weak hashes for newly registered users.

Step 6: Benchmark hashing on your infrastructure

The right cost parameters depend on your hardware, concurrent login volume and latency requirements.

<?php
declare(strict_types=1);

$options = [
    'memory_cost' => 19 * 1024,
    'time_cost' => 2
];

$start = hrtime(true);

$hash = password_hash(
    'benchmark-password',
    PASSWORD_ARGON2ID,
    $options
);

$milliseconds = (hrtime(true) - $start) / 1_000_000;

echo round($milliseconds, 2) . ' ms';
Technical workflow illustration

Run this only in a controlled environment, not as a public web endpoint. Measure verification too, and repeat under representative load. A setting that looks fast in isolation can exhaust RAM when many requests arrive together.

OWASP recommends balancing security with operational capacity and generally keeping individual hashing operations below one second.

Common password hashing mistakes

Adding a fixed salt manually. PHP already generates secure salts for its password API. A fixed salt removes an important protection.

Using raw MD5, SHA-1 or SHA-256. These algorithms are far too fast for password storage on their own.

Ignoring bcrypt's 72-byte limit. Multi-byte UTF-8 characters can reach this limit sooner than users expect.

Choosing extreme cost settings. Excessive memory or CPU demands can create a denial-of-service risk at authentication endpoints.

Logging submitted passwords. Avoid exposing credentials through debugging logs, monitoring systems or error reports.

Assuming password hashing solves authentication security. Rate limiting, breach response, session security and multifactor authentication still matter.

Should you use a pepper?

A pepper is an additional shared secret kept outside the password database. Unlike a salt, it is not stored alongside each hash.

A properly designed pepper can provide defense in depth if an attacker steals only the database. But peppering introduces key-management and rotation complexity: losing or rotating a pepper may require password resets.

Do not improvise by concatenating a hardcoded secret to every password. Follow a documented strategy, store secrets separately and plan for rotation. OWASP discusses pre-hashing and post-hashing pepper approaches.

A practical password hashing policy

For a new PHP application, prefer Argon2id when available, begin with an OWASP-aligned configuration, benchmark it and store the complete encoded hash. Where Argon2id is unavailable, bcrypt through PHP's password API is a practical alternative if its cost and input limit are understood.

For an existing application, keep verifying supported legacy hashes while upgrading them after successful authentication. Avoid disruptive migrations when the original password is not available.

Design for upgrades from the beginning. Hardware and recommendations change; your authentication system should be able to adopt better parameters and algorithms without changing every user's password at once.

Frequently asked questions

Is Argon2id better than bcrypt?

Argon2id offers configurable memory hardness and is OWASP's preferred choice for new password storage implementations.

Does PHP use Argon2id by default?

No. PHP's PASSWORD_DEFAULT currently selects bcrypt. Use PASSWORD_ARGON2ID explicitly when supported.

Can I migrate bcrypt hashes without password resets?

Yes. Verify the existing hash, then rehash the submitted password after a successful login.

Should I store the salt separately?

No. PHP's password hashing API generates the salt and stores the required information in the encoded hash.

Is SHA-256 secure for passwords?

Not by itself. Use a dedicated adaptive password hashing algorithm rather than raw SHA-256.

Official references