How to create / generate .htpasswd password with PHP dynamically?

The easy way to add a username and password pair in the .htpasswd file is to use an online password generator tool that converts the clear text password into its hash, a.k.a. the encrypted password. The problem with this approach is that you have to manually create the pair and append it to .htpasswd. Is there a way to dynamically generate encrypted passwords for .htpasswd in PHP?

According to http://httpd.apache.org/docs/2.2/misc/password_encryptions.html, we have come up with the following solution:

$pass = 'YourClearTextPasswordString';
$hash = base64_encode(sha1($pass, true));
$encoded = '{SHA}'.$hash;
echo $encoded;

And $encoded is the result we need, which would look something like:

{SHA}hNz9UE9WLiMlzYI+LRtwr0U+DHY=

Suppose the username is ‘manager’ and you can add the following line at the end of your .htpasswd file to make the credentials in effect:

manager:{SHA}hNz9UE9WLiMlzYI+LRtwr0U+DHY=

You can also write / append this to the file by PHP but that’s not covered here.

What’s better, the SHA1 algorithm is much more advanced than DES which most of the online .htpasswd generation tool still uses to generate the hash string of the clear password for you. DES supports only 8 digits and that’s where lengthy passwords fail.

1 thought on “How to create / generate .htpasswd password with PHP dynamically?”

Comments are closed.

Scroll to Top