PHP / Encryption / htpasswd
Snippet details
ID: 1
Viewed: 1864
Added: 2001-11-13
Version:
Sorry no demo
You can use an existing .htpasswd file with your PHP-based authentication scripts by using a combination of the substr() and the crypt() function to match the value entered by the user for $PHP_AUTH_PW, and an entry in the .htpasswd file.
General Details
Snippet uploaded by: snippet
Email : webmaster@snippetlibrary.com
Snippet By: snippet
<!---Head--->
none
<!---Body--->
<?
If (!isset($PHP_AUTH_USER)) {
header('WWW-Authenticate: Basic realm="Private"');
header('HTTP/1.0 401 Unauthorized');
echo 'Authorization Required.';
Exit;
} Else If (isset($PHP_AUTH_USER)) {
$filename = "/path/to/.htpasswd";
$fp = fopen($filename, "r");
$file_contents = fread($fp, filesize($filename));
fclose($fp);
// Place each line in user info file into an array
$Line = explode("n", $file_contents);
// For as long as $i is less than the size of the $line array,
// explode each array element into a username and password
// pair and attempt to match to $PHP_AUTH_USER and
// $PHP_AUTH_PW values
$i = 0;
While($i <= sizeof($Line)) {
$data_pair = explode(":", $Line[$i]);
If ($data_pair[0] == "$PHP_AUTH_USER") {
// get salt from $data_pair[1]
$salt = substr($data_pair[1], 0, 2);
// encrypt $PHP_AUTH_PW based on $salt
$enc_pw = crypt($PHP_AUTH_PW, $salt);
// try to match encrypted passwords
If ($data_pair[1] == "$enc_pw") {
$auth = 1;
break;
} Else {
$auth = 0;
}
} Else {
$auth = 0;
}
$i++;
}
// check value of $auth
If ($auth == "1") {
echo "You're authorized!
";
} Else {
header('WWW-Authenticate: Basic realm="Private"');
header('HTTP/1.0 401 Unauthorized');
echo 'Authorization Required.';
Exit;
}
}
?>
No Reviews to show
