0
0
PhpHow-ToBeginner · 3 min read

How to Use password_hash in PHP for Secure Passwords

Use password_hash in PHP to create a secure hashed password by passing the plain password and a hashing algorithm like PASSWORD_DEFAULT. This function automatically handles salt and returns a safe hash string for storage.
📐

Syntax

The password_hash function takes at least two arguments: the plain password string and the hashing algorithm constant. It returns a hashed password string that includes the salt and algorithm info.

  • password: The plain text password to hash.
  • algo: The algorithm to use, usually PASSWORD_DEFAULT for the current best option.
  • options (optional): An array to specify options like cost for algorithm strength.
php
string password_hash(string $password, int $algo, array $options = [])
💻

Example

This example shows how to hash a password and then verify it using password_verify. It demonstrates storing the hash and checking a user login password safely.

php
<?php
$password = 'mySecret123';
// Hash the password using the default algorithm
$hash = password_hash($password, PASSWORD_DEFAULT);
echo "Hashed password: $hash\n";

// Later, verify the password entered by user
$enteredPassword = 'mySecret123';
if (password_verify($enteredPassword, $hash)) {
    echo "Password is valid!";
} else {
    echo "Invalid password.";
}
Output
Hashed password: $2y$10$... (hash string varies) Password is valid!
⚠️

Common Pitfalls

Common mistakes include:

  • Trying to manually add salt instead of letting password_hash handle it.
  • Using weak algorithms or outdated methods like md5 or sha1.
  • Not verifying passwords with password_verify, which can cause security issues.
  • Storing plain passwords or hashes without proper database security.
php
<?php
// Wrong way: manual salt and md5 (not secure)
$password = 'mypassword';
$salt = 'randomsalt';
$badHash = md5($salt . $password);

// Right way: use password_hash
$goodHash = password_hash($password, PASSWORD_DEFAULT);
📊

Quick Reference

FunctionPurposeNotes
password_hashCreate a secure password hashUse PASSWORD_DEFAULT for best algorithm
password_verifyCheck if a password matches a hashAlways use to verify passwords
password_needs_rehashCheck if hash needs updatingUse when algorithm or cost changes

Key Takeaways

Always use password_hash with PASSWORD_DEFAULT to securely hash passwords.
Never create your own salt; password_hash handles it automatically.
Use password_verify to check passwords safely against stored hashes.
Avoid outdated hashing functions like md5 or sha1 for passwords.
Consider password_needs_rehash to update hashes when algorithms improve.