Generating bcrypt .htpasswd passwords using PHP

In my previous post we saw how to generate .htpasswd file using crypt and apr1-md5 algorithm in PHP. However, now there is a more secure BCRYPT algorithm that can be used since apache 2.4 for passwords in .htpasswd. In this post we will generate .htpasswd file using the BCRYPT algorithm in PHP.

The command to generate the htpasswd using BCRYPT algorithm in apache is

htpasswd -B /usr/local/etc/apache/.htpasswd user1

In PHP 5.5+ a new password hashing API was added. We are going to use the password_hash() function of the API to generate our .htpasswd file in this post. Here is the code that we can use to generate a BCRYPT password hash.

// Password to be used for the user
$username = 'user1';
$password = 'password1';

// Encrypt password
$encrypted_password = password_hash($password, PASSWORD_BCRYPT);

// Print line to be added to .htpasswd file
echo $username . ':' . $encrypted_password;
Sample Output:

We can use this simple function to generate BCRYPT password hashes using PHP to be used for .htpasswd file. It is recom

Related posts:

  1. PHP 5.5 Password Hashing API
  2. How to generate passwords for .htpasswd using PHP
  3. .htaccess tips
  4. more .htaccess tips

Leave a Reply