W3docs

How to Use bcrypt to Hash Passwords in PHP

There is a password hashing technique, used for building the security of passwords. It is called bcrypt. Here, you will learn how to use it in PHP.

Storing passwords in plain text is insecure. While some developers historically did this for easy password recovery, modern best practices require secure hashing. The bcrypt algorithm is widely used to protect passwords from attacks by storing them in a hashed format. This snippet demonstrates how to use the password_hash() function to hash passwords in PHP.

The syntax of the <kbd class="highlighted">password_hash()</kbd> function looks as follows:

php password_hash() function syntax

string password_hash( $password, $algo, $options )

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

It accepts three parameters: password, algo, and options.

The first parameter (password) specifies the user's password. The second parameter (algo) is a password algorithm constant that determines which hashing algorithm to use. The third parameter (options) is an optional associative array containing algorithm-specific options (such as the cost factor).

On success, the function returns a string containing the hashed password, or false on failure.

Below, you can check out several examples of using the <kbd class="highlighted">password_hash</kbd> function in PHP.

php password_hash example

<?php

echo password_hash("GFG@123", PASSWORD_DEFAULT);

php password_hash output

$2y$10$vB5kRTOjfSr5kI3YsqqDnO7nA1TWaS84ELRvhgCv0EyLMwYkKvgni

php using the password_hash function

<?php

$options = [
  'cost' => 12,
];

echo password_hash("GFG@123", PASSWORD_BCRYPT, $options);

php using the password_hash function, output

$2y$12$sw6OunkXaRsTghr6Ku1pq.IJSGaZuBbsJ7Uzb3BWPuuJNOsG0y7rW

About the password_hash() Function in PHP

The PHP <kbd class="highlighted">password_hash()</kbd> function is an inbuilt function used for generating a new password hash. It implements a strong and secure hashing system. It is the recommended modern alternative to the older <kbd class="highlighted">crypt()</kbd> function. While both functions use compatible hashing formats, password_hash() is preferred for new applications due to its simpler API and automatic handling of salt and algorithm selection.

To learn more about the <kbd class="highlighted">password_hash()</kbd> function, check out this page.