The code below comes from a Webmonkey tutorial ( with a couple of
modifications tagged by // which I do not think are relevant)
I cannot get it to work. Any help would be appreciated.
The php file is in the same directory as the .htpasswd file and there is no
..htaccess file.
When I click on a link to the file the initial header('WWW-Authenticate:
Basic realm="My Realm"') dialog pops up and asks for username and
password.
When I enter them, the final header('WWW-Authenticate: Basic
realm="Private" ') dialog pops up 3 times before rejecting the
authentication.
Using alerts I have tracked through the code and everything seems ok right
to the end:
the contents of .htpasswd are correctly read into $file_contents and
exploded into $line;
when I check $data_pair[1] and $enc_pw in alert boxes they
are the same;
but the condition if ($data_pair[1] == $enc_pw ) fails and the
Authorization Required message is echoed along with the two identical
strings representing $data_pair[1] and $enc_pw
<?php
if (!isset($_SERVE R['PHP_AUTH_USER'])) { //was
!isset($PHP_AUT H_USER)
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';
exit;
} else if (isset($_SERVER['PHP_AUTH_USER'])) {
$filename = ".htpasswd" ;
$fp = fopen($filename , "r");
$file_contents = fread($fp, filesize($filen ame));
fclose($fp);
$line = explode("\n", $file_contents) ;
$i = 0;
while($i < sizeof($line))
{ //was while($i <=
sizeof($line)) {
$data_pair = explode(":", $line[$i]);
if ($data_pair[0] =="$PHP_AUTH_US ER") {
$salt = substr($data_pa ir[1], 0, 2);
$enc_pw = crypt("$PHP_AUT H_PW", $salt);
if ($data_pair[1] == $enc_pw ) {
$auth = 1;
break;
} else {
$auth = 0;
}
} else {
$auth = 0;
}
$i++;
}
if ($auth == "1") {
echo "You're authorized!";
} else {
header('WWW-Authenticate: Basic realm="Private" ');
header('HTTP/1.0 401 Unauthorized');
echo 'You have not supplied the <strong>Authori zation
Required</strong> to enter this site.';
echo $enc_pw."<br>";
echo $data_pair[1]; // confirms that $enc_pw and
$data_pair[1] are apparently the same
exit;
}
}
?>
Comment