PHP password_hash

Summary: in this tutorial, you’ll learn how to use the PHP password_hash() function to create a password hash.

Introduction to the PHP password_hash() function

The password_hash() function allows you to create a password hash using a secure one-way hashing algorithm.

Here’s the syntax of the password_hash() function:

password_hash(string $password, string|int|null $algo, array $options = []): string
Code language: PHP (php)

The password_hash() function has the following parameters:

  • $password is the plain text password to be hashed.
  • $algo is a constant that specifies the hashing algorithm.
  • $options is an associative array of options of each algorithm. If you omit the $options, the function will generate a random salt and default cost for hashing.

The password_hash() function returns the hashed password.

hashing algorithms

The password_hash() function supports the following hashing algorithms:

ConstantHashing Algorithm

PHP password_hash() function example

The following example shows how to generate the hashed password from the password 'Password1':

<?php $password = 'Password1'; echo password_hash($password, PASSWORD_DEFAULT);
Code language: PHP (php)


Code language: plaintext (plaintext)

This example uses the PASSWORD_DEFAULT algorithm, which instructs the password_hash() function to use the bcrypt hashing algorithm.

In practice, you’ll use the password_hash() function to hash a password before storing it in the database. And, you’ll use the password_verify() function to match the plain text password provided by users with the hashed password stored in the database.

Besides hashing a plain text password, you can use the password_hash() to securely hash any token you want to store in the database.


  • Use the PHP password_hash() function to create a hash password using a secure one-way hashing algorithm.
Did you find this tutorial useful?