Advertising disclosure

Hosting Canada is community-supported. We may earn a commission when you make a purchase through one of our links. Read Disclosure.

How to create a password for a .htpasswd file using PHP

A user emailed me and asked how to create a password for a .htpasswd file using PHP. It is actually very simple.

Below is a PHP script that generates a password for .htpasswd from the clear text password stored in $clearTextPassword.

Please note: For Apache servers running on Windows you have to use the htpasswd program to generate passwords, or use the htpasswd generator.

<?php
// Password to be encrypted for a .htpasswd file
$clearTextPassword = 'some password';

// Encrypt password
$password = crypt($clearTextPassword, base64_encode($clearTextPassword));

// Print encrypted password
echo $password;
?>

How to use the code:

  1. Copy the above the code and paste it into your favorite text editor (ie notepad).
  2. Change “some password” to the password you want to encrypt.
  3. Save the code in file called htpasswd.php.
  4. Upload htpasswd.php to your webserver.
  5. Execute the code by going to http://www.your-domain.com/htpasswd.php
  6. The outputted text is your encrypted password.

You can of course also use the htpasswd-generator if you don’t want your own script.