How do I hash a password in PHP?

Short answer

Use password_hash($password, PASSWORD_DEFAULT) to store and password_verify($input, $hash) to check. It salts automatically and the salt is embedded in the output.

php
// Registering
$hash = password_hash($plainPassword, PASSWORD_DEFAULT);
// store $hash in a VARCHAR(255) column

// Logging in
if (password_verify($submitted, $hash)) {
    // correct
}

That is the entire API. No salt to generate, no algorithm to choose, no comparison to write.

#Why not md5 or sha1?

They are designed to be fast, which is precisely wrong for passwords. A modern GPU tries billions of MD5 guesses per second. password_hash uses bcrypt (or Argon2), which is deliberately slow and tunable.

#Do not add your own salt

password_hash generates a cryptographically secure random salt per password and stores it inside the returned string. Passing your own is unnecessary and the salt option was removed for that reason.

#Column size

Use VARCHAR(255). Bcrypt output is 60 characters today, but PASSWORD_DEFAULT is explicitly allowed to change to a longer algorithm in future PHP versions. A 60-character column will silently truncate hashes and break every login.

#Upgrading hashes on login

php
if (password_verify($submitted, $hash)) {
    if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
        $newHash = password_hash($submitted, PASSWORD_DEFAULT);
        // save $newHash
    }
}

This is the only moment you have the plaintext, so it is the only moment you can re-hash.