htpasswd and php
by AndyMac
I thought I could help some folks with some basic web auth functions.
I often find that I want to check out whether a user has the permissions to do something, but might not want to generate htaccess rules for each and every script. Instead, I want my server side scripts to be able to do these tests and continue or fail correctly.
To that end, you need to be able to read the .htpasswd file.
I put together a real quick htpasswd “helper” file that contains a few functions for adding users, changing passwords, checking whether a user has correctly entered information, and things like that.
For this particular example, we want to take a username and a password (in plain text, which is not as safe … you could encrypt it before you send the information, but then, if you’re using htpasswd, you’re already somewhat on the insecure side of “locked down”) and ask whether the username and password are in the htpasswd file.
function validate($file, $username, $password) {
$lines = file($file);
for ($ii = 0; $ii < count($lines); $ii++) {
if (preg_match("/:/",$lines[$ii])) {
$lines[$ii] = trim($lines[$ii]);
list($user,$pass) = explode(":",$lines[$ii]);
if ($user == $username) {
$password = crypt(rtrim($password),substr($pass,0,2));
if ($pass == $password) {
return true;
} else {
return false;
}
}
}
}
}
The key here is the “crypt” command that encrypts the password using the first two letters of the password as the seed.
Give it a shot, let me know how it works for you!