How to programmatically build an APR1-MD5 using PHP How to programmatically build an APR1-MD5 using PHP apache apache

How to programmatically build an APR1-MD5 using PHP


It turns out I made a mistake and this function does in fact create working APR1 htpasswd entries. They do look different to the ones Apache creates but they do work.


Look for existing components that do it on sites like phpclasses.org. One example: http://www.phpclasses.org/browse/package/5066.html.


Thanks you! It works like a charm.

Just a small comment: The salt can also contain "./" and "A..Z" besides "a..z0..9", so it is the same string as the 'translate-to' string in the last line. And sometimes you want to set the salt in addition, to create reproducable results, like:

function crypt_apr1_md5( $plainpasswd, $salt = '' ) {
$translateTo = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if ( $salt == '' ) { $salt = substr(str_shuffle($translateTo), 0, 8); }

...

$tmp = strtr(strrev(substr(base64_encode($tmp), 2)), "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", $translateTo);
return '$apr1$'.$salt.'$'.$tmp;
}