How to Securely Hash Passwords in PHP

Use PHP's password_hash() and password_verify() functions to store and check passwords securely — never store plain text or use md5/sha1 for passwords.

Published September 18, 2026

Hash passwords with password_hash() and verify them with password_verify(). Never use md5 or sha1, and never store plain text. PHP picks a strong algorithm and salt for you.

The concept

A hash is a one-way function: you can check a password against it, but not recover the password. password_hash uses bcrypt (or Argon2) with a random salt built into the output string.

These algorithms are deliberately slow to make brute-forcing expensive. As hardware improves, use password_needs_rehash to upgrade old hashes on the next login.

Register and log in

hashstoreFormpasswordpassword_hashbcrypt + saltDatabase$2y$10$…
The plain password is never stored.

Practical examples

Register

$hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
// INSERT INTO users (email, password) VALUES (?, ?)

Login

if (password_verify($_POST['password'], $row['password'])) {
  session_regenerate_id(true);
  $_SESSION['uid'] = $row['id'];
}

Upgrade old hashes

if (password_needs_rehash($row['password'], PASSWORD_DEFAULT)) {
  $new = password_hash($_POST['password'], PASSWORD_DEFAULT);
  // UPDATE users SET password = ? WHERE id = ?
}

Common mistakes

  • Using md5() or sha1() — they are fast and easily cracked.
  • Adding your own salt; password_hash already does it.
  • Limiting password length too low, or truncating (bcrypt uses the first 72 bytes).
  • Comparing hashes with == instead of password_verify.

Key takeaways

  • password_hash + password_verify.
  • Store the full result in a VARCHAR(255).
  • Rehash on login when the algorithm improves.

FAQ

Bcrypt or Argon2?

PASSWORD_DEFAULT is a safe choice; PASSWORD_ARGON2ID is also good if available.

How long is the hash?

Bcrypt gives 60 characters; use VARCHAR(255) for future algorithms.

More PHP articles