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:
Constant | Hashing Algorithm |
---|---|
PASSWORD_DEFAULT | bcrypt |
PASSWORD_BCRYPT | CRYPT_BLOWFISH |
PASSWORD_ARGON2I | Argon2i |
PASSWORD_ARGON2ID | Argon2id |
PHP password_hash() function example
The following example shows how to generate the hashed password from the password 'Password1'
:
$password = 'Password1';
echo password_hash($password, PASSWORD_DEFAULT);
Code language: PHP (php)
Output:
$2y$10$hnQY9vdyZUcwzg2CO7ykf.a4iI5ij4Pi5ZwySwplFJM7AKUNUVssO
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.
Summary
- Use the PHP
password_hash()
function to create a hash password using a secure one-way hashing algorithm.