CodeBlanks Logo Icon CodeBlanks

Hashing with password_hash()

PHP course · Advanced · Lesson 60/92

Learn secure password hashing with password_hash() and PASSWORD_DEFAULT.

What does password_hash do?

Storing passwords as plain text is a huge risk; if the database leaks, every account is exposed. The password_hash() function turns a password into a one-way string (hash); the original password cannot be recovered.

As the second argument you pass PASSWORD_DEFAULT. PHP maps this to the current recommended algorithm; today that is bcrypt. argon2 is also available as an alternative. The salt is added automatically; you do not need to generate it.

Why not md5 or sha1?

In old code you may see md5() or sha1(). They are fast, so they are weak against brute force; without a salt they can be broken with rainbow tables. Do not use them for password storage.

password_hash() uses cost-based algorithms instead. Each call generates a new salt embedded in the hash; the same password hashed twice yields different results.

Exercise Produce a hash with password_hash

Hash the $password variable with password_hash. Use PASSWORD_DEFAULT as the second argument. Print the length of the resulting hash with strlen.

Show example solution
Write $hash = password_hash($password, PASSWORD_DEFAULT);. Then print the length with echo strlen($hash) . "\n";.
Example solution:
<?php
$password = "gizli123";
$hash = password_hash($password, PASSWORD_DEFAULT);
echo strlen($hash) . "\n";

Test yourself

  1. What does PASSWORD_DEFAULT do?

    • It encrypts the password two-way
    • It picks the current recommended algorithm
    • It shortens the hash
    • It saves the hash to the database
    Show answer

    It picks the current recommended algorithm — Correct. PASSWORD_DEFAULT maps to the current recommended algorithm (bcrypt).

  2. Complete the password_hash call

    $hash = ____($password, PASSWORD_DEFAULT);
    Show answer
    $hash = password_hash($password, PASSWORD_DEFAULT);
  3. Match the password_hash concepts

    password_hash
    Hashes the password
    PASSWORD_DEFAULT
    Recommended algorithm
    salt
    Random salt
    bcrypt
    Cost-based algorithm

All lessons in Advanced