Skip to content

How to Use bcrypt to Hash Passwords 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 password_hash() function looks as follows:

php password_hash() function syntax

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

<div class="alert alert-info flex not-prose"> Watch a course 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 password_hash function in PHP.

php password_hash example

php
<?php

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

php password_hash output

console
$2y$10$vB5kRTOjfSr5kI3YsqqDnO7nA1TWaS84ELRvhgCv0EyLMwYkKvgni

php using the password_hash function

php
<?php

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

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

php using the password_hash function, output

console
$2y$12$sw6OunkXaRsTghr6Ku1pq.IJSGaZuBbsJ7Uzb3BWPuuJNOsG0y7rW

About the password_hash() Function in PHP

The PHP password_hash() 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 crypt() 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 password_hash() function, check out this page.

Dual-run preview — compare with live Symfony routes.