How to Securely Hash Passwords in PHP (and When to Use Encryption)

If you searched for how to encrypt a password in PHP, the most important thing to know is this: you should not encrypt user passwords at all. You should hash them. This guide explains the difference, shows the correct code with PHP’s built-in password_hash() and password_verify() functions, covers how to migrate old MD5 or SHA1 passwords, and shows how to encrypt other sensitive data (such as API keys) properly when you really do need to read it back.

Updated for current PHP. Earlier versions of this article used the mcrypt extension and fast hashes like MD5. mcrypt was deprecated in PHP 7.1 and removed in PHP 7.2, and MD5/SHA1 are unsafe for passwords. Do not use code that relies on them.

Hashing vs. Encryption: Which One Do Passwords Need?

Encryption is reversible. Anyone who has the key can turn the ciphertext back into the original text. That is exactly what you want for data you must read again later, and exactly what you do not want for passwords: if an attacker steals your database and your key, every password is exposed.

Hashing is one-way. A password hash cannot be turned back into the password. To log a user in, you hash what they typed and check whether it matches the stored hash. Your application never needs to know the real password, so it never stores it.

  • User passwords → hash with password_hash().
  • Data you must read back (API keys, tokens for third-party services, personal data fields) → encrypt with a modern authenticated cipher.
  • Never encrypt passwords, store them in plain text, or “hide” them with base64_encode(), which is encoding, not security.

Why MD5, SHA1 and SHA256 Are Not Enough

MD5, SHA1 and even SHA256 are general-purpose hashes designed to be fast. That is a problem for passwords. Modern GPUs can try billions of MD5 or SHA1 guesses per second, so a stolen database of fast hashes can be cracked quickly with wordlists and brute force, especially when passwords are short or reused.

Password hashing algorithms such as bcrypt and Argon2 are deliberately slow and tunable, and they add a unique random salt to every password automatically. The salt stops attackers from using precomputed tables and means two users with the same password get different hashes. PHP handles all of this for you.

How to Hash a Password in PHP with password_hash()

password_hash() is available in every supported PHP version. Use PASSWORD_DEFAULT so PHP can move to a stronger algorithm in future versions without code changes (today the default is bcrypt).

<?php
$password = $_POST['password'];

// Hash the password before saving it
$hash = password_hash($password, PASSWORD_DEFAULT);

// Save $hash in the database, e.g. in a `password_hash` column

A bcrypt hash looks like $2y$12$.... It already contains the algorithm, the cost and the salt, so you store just this one string. Use a VARCHAR(255) column, because future default algorithms may produce longer hashes.

CREATE TABLE users (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(255) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL
);

Choosing the cost

The cost controls how slow each hash is. PHP 8.4 raised the default bcrypt cost from 10 to 12. A good rule is to pick the highest cost that keeps hashing under roughly 100–300 ms on your production server. You can set it explicitly:

<?php
$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);

Using Argon2id

If your PHP build includes Argon2 support (PHP 7.3+ compiled with libargon2, common on modern Linux packages), Argon2id is an excellent choice because it is also memory-hard, which makes GPU cracking more expensive:

<?php
if (defined('PASSWORD_ARGON2ID')) {
    $hash = password_hash($password, PASSWORD_ARGON2ID);
} else {
    $hash = password_hash($password, PASSWORD_DEFAULT);
}

bcrypt limit: bcrypt only uses the first 72 bytes of a password. That rarely matters for normal passwords, but if you allow very long passphrases, prefer Argon2id.

How to Check a Password with password_verify()

At login, never hash the input and compare strings yourself. Use password_verify(), which reads the algorithm and salt from the stored hash and compares in constant time to avoid timing attacks.

<?php
$stmt = $pdo->prepare('SELECT id, password_hash FROM users WHERE email = ?');
$stmt->execute([$_POST['email']]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user && password_verify($_POST['password'], $user['password_hash'])) {
    // Correct password: start the session
    session_regenerate_id(true);
    $_SESSION['user_id'] = $user['id'];
} else {
    // Use one generic message so you don't reveal which emails exist
    echo 'Invalid email or password.';
}

Keep Hashes Up to Date with password_needs_rehash()

When you raise the cost or PHP changes its default algorithm, existing hashes stay as they were. password_needs_rehash() lets you upgrade each user transparently the next time they log in successfully, because that is the only moment you have their plain password:

<?php
if (password_verify($input, $user['password_hash'])) {
    if (password_needs_rehash($user['password_hash'], PASSWORD_DEFAULT)) {
        $newHash = password_hash($input, PASSWORD_DEFAULT);
        $pdo->prepare('UPDATE users SET password_hash = ? WHERE id = ?')
            ->execute([$newHash, $user['id']]);
    }
    // log the user in
}

How to Migrate Old MD5 or SHA1 Passwords

If an older application stores md5($password) or sha1($password), you can move every user to password_hash() without forcing a reset. Check the legacy hash once at login, then replace it:

<?php
$stored = $user['password_hash'];
$input  = $_POST['password'];

$isLegacyMd5 = (bool) preg_match('/^[a-f0-9]{32}$/i', $stored);

if ($isLegacyMd5 && hash_equals($stored, md5($input))) {
    // Correct legacy password: upgrade it immediately
    $newHash = password_hash($input, PASSWORD_DEFAULT);
    $pdo->prepare('UPDATE users SET password_hash = ? WHERE id = ?')
        ->execute([$newHash, $user['id']]);
    $ok = true;
} else {
    $ok = password_verify($input, $stored);
}

Users who never log in again will keep their weak hash. For those accounts, a common approach is to wrap the old hash right away (store password_hash($md5Hash, PASSWORD_DEFAULT) and verify with password_verify(md5($input), $stored)), or expire them and require a password reset.

Hashing Passwords in Laravel

Laravel uses the same PHP functions under the hood, configured in config/hashing.php (bcrypt by default, Argon2 optional):

<?php
use Illuminate\Support\Facades\Hash;

$hash = Hash::make($request->password);

if (Hash::check($request->password, $user->password)) {
    // valid
}

if (Hash::needsRehash($user->password)) {
    $user->password = Hash::make($request->password);
    $user->save();
}

Laravel’s built-in authentication (Breeze, Jetstream, Fortify) already does this, so only write it yourself for custom login flows.

When You Do Need Encryption: Encrypting Other Data in PHP

Some secrets must be readable again: an SMTP password your app uses to send mail, a third-party API key, or a sensitive field you display back to the account owner. For these, use authenticated encryption, which both hides the data and detects tampering.

Option 1: libsodium (recommended)

The Sodium extension has been bundled with PHP since 7.2 and is the simplest safe choice:

<?php
// Generate once and store securely (environment variable or secrets manager)
$key = sodium_crypto_secretbox_keygen();

function encrypt_value(string $plain, string $key): string {
    $nonce  = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
    $cipher = sodium_crypto_secretbox($plain, $nonce, $key);
    return base64_encode($nonce . $cipher);
}

function decrypt_value(string $encoded, string $key): string|false {
    $raw    = base64_decode($encoded, true);
    $nonce  = substr($raw, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
    $cipher = substr($raw, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
    return sodium_crypto_secretbox_open($cipher, $nonce, $key);
}

Option 2: OpenSSL with AES-256-GCM

If you need AES specifically, use GCM mode, which includes an authentication tag. Avoid ECB mode and avoid CBC without a separate MAC.

<?php
// 32 random bytes, generated once and stored securely
$key = random_bytes(32);

function encrypt_aes_gcm(string $plain, string $key): string {
    $iv  = random_bytes(12);
    $tag = '';
    $cipher = openssl_encrypt($plain, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
    return base64_encode($iv . $tag . $cipher);
}

function decrypt_aes_gcm(string $encoded, string $key): string|false {
    $raw    = base64_decode($encoded, true);
    $iv     = substr($raw, 0, 12);
    $tag    = substr($raw, 12, 16);
    $cipher = substr($raw, 28);
    return openssl_decrypt($cipher, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
}

In Laravel, use Crypt::encryptString() and Crypt::decryptString(), or the encrypted model cast. They use your APP_KEY and authenticated encryption for you.

Key management matters more than the algorithm. Keep keys out of your code and out of the database that holds the encrypted data. Use environment variables or a secrets manager, restrict who can read them, and plan how you would rotate a key if it leaked.

What About MySQL Functions?

Do not hash or encrypt application passwords inside MySQL with functions like MD5(), SHA1() or AES_ENCRYPT(). The plain password travels to the database server and can end up in query logs, and these functions are not password hashing algorithms. MySQL’s old PASSWORD() function was removed in MySQL 8.0. Hash in PHP with password_hash() and store only the result.

Password Security Checklist

  • Hash passwords with password_hash() using PASSWORD_DEFAULT or Argon2id.
  • Verify with password_verify(); never compare hashes with ==.
  • Upgrade old hashes with password_needs_rehash() at login.
  • Store hashes in a VARCHAR(255) column.
  • Never log, email or display a user’s password.
  • Serve login and registration pages only over HTTPS.
  • Rate-limit login attempts and add multi-factor authentication for admin accounts.
  • Use prepared statements for every query that touches user input.
  • Encrypt other reversible secrets with Sodium or AES-256-GCM and keep the keys outside the database.

Frequently Asked Questions

Can I decrypt a password hash created with password_hash()?

No. That is the point of hashing. The only way to “recover” a password from a strong hash is to guess it, and bcrypt or Argon2 make guessing slow. If a user forgets their password, send a secure reset link instead.

Do I need to create and store a salt myself?

No. password_hash() generates a random salt for every password and stores it inside the hash string. The salt option was deprecated in PHP 7.0 and is ignored in PHP 8.

Is SHA256 with a salt good enough?

It is better than plain MD5, but it is still a fast hash and can be cracked far more quickly than bcrypt or Argon2. Use a dedicated password hashing function instead of building your own.

What does the password_hash output contain?

For bcrypt, the string includes the algorithm identifier ($2y$), the cost, a 22-character salt and the hash itself, all in one 60-character value. Argon2id hashes also include their memory, time and parallelism settings.

Share this Article

S.A. Dedar

S.A. Dedar writes about AI automation, AI agents and how digital professionals can adapt their careers as AI changes the work. He has spent more than a decade working hands-on with websites, SEO, paid advertising, IT projects and business automation, and has written on sadedar.com since 2015. His guides focus on practical, tested workflows rather than hype.