Using PHP to generate htpasswd format passwords

December 28th 2012

.htpasswd files are annoying. There are loads of tools out there to create them, but I wanted to take a second to show you how easy it is to create them in PHP.

First, the basics:

PHP Code:
<?php
// Plain text password
$plain 'top secret password';

// Htpasswd password
$password crypt($plainbase64_encode($plain));

print(
$password);

Above you've got a htpasswd format password ready to use in your htpasswd file.

Putting this into a simple function makes it a little easier.

PHP Code:
<?php
function htpasswd($password) {
    return 
crypt($passwordbase64_encode($password));
}

print(
htpasswd('top secret password'));

Using this, you can create a simple htaccess file with:

Text Snippet:
AuthType Basic
AuthName "Super Secret"
AuthUserFile /my/directory/.htpasswd
Require valid-user

Then create the htpasswd file with:

Text Snippet:
USERNAME:PASSWORD

gggggggggggg commented on Jul 1st 2013

Good post, thanks

Mitar commented on Oct 21st 2013

Superior thinking demonstrated above. Thanks!