How to Use bcrypt to Hash Passwords in PHP

It is not a secret that storing passwords in a clear text is not secure. However, sometimes developers do that to make the site easy for password recovery. There exists a password hashing technique that is used for building the security of passwords. It is called bcrypt. You can use it for protecting the password from different attacks. With it, the password is kept in a bcrypted format. In this snippet, we will demonstrate the way of using the bcrypt technique for hashing passwords. It can be done with the password_hash() function.

The syntax of the password_hash() function looks as follows:

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

Watch a course Learn object oriented PHP

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

The first parameter (password) keeps the user password. The second one (algo) is the password algorithm constant, used in the process of denoting the algorithm to be used once the password hashing occurs. The third parameter (options) is an associative array, containing options.

On success, it returns true, and returns false, otherwise.

Below, you can check out several examples of using the password_hash function in PHP.

<?php

echo password_hash("GFG@123", PASSWORD_DEFAULT);
$2y$10$vB5kRTOjfSr5kI3YsqqDnO7nA1TWaS84ELRvhgCv0EyLMwYkKvgni
<?php

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

echo password_hash("GFG@123", PASSWORD_BCRYPT, $options);
$2y$12$sw6OunkXaRsTghr6Ku1pq.IJSGaZuBbsJ7Uzb3BWPuuJNOsG0y7rW

About the password_hash() Function in PHP

The PHP password_hash() function is an inbuilt function, applied for generating a new password hash. A quite strong and secure hashing system is used by it. It can be compared, for, instance, with the crypt() function. Moreover, the hashes generated by the latter can be used with password_hash() and vice versa.

To Learn more about the password_hash() function, check out this page.