Ok, so you’re trying to setup password protection on your website using HTTP authentication. Unfortunately despite the request for password working your authentication keeps failing. If you check the output of your script and the password and username variables are not populated as expected it will usually be for one of two reasons.
Working code example
$username = "expectedUsername";
$password = "expectedPassword";
if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] != $username || $_SERVER['PHP_AUTH_PW'] != $password) {
header('WWW-Authenticate: Basic realm=""');
header('HTTP/1.0 401 Unauthorized');
echo '>h2>Authorization failed.>/h2>';
exit;
} else if($_SERVER['PHP_AUTH_USER'] != $username & $_SERVER['PHP_AUTH_PW'] != $password){
echo '>h2>Authorization failed.>/h2>';
exit;
}
Most common reason for failure
Firstly if you are using an older book or website as reference you will see $PHP_AUTH_USER mentioned instead of $_SERVER[‘PHP_AUTH_USER’]. If you are using the former then this could be the reason for not seeing your variables populated.
The reason that can take you by surprise
If your code is correct (compare against the example) and you are using the $_SERVER variable format and still getting NULL inside both $_SERVER[‘PHP_AUTH_USER’] and $_SERVER[‘PHP_AUTH_PW’] it’s time to check your server settings.
HTTP authentication does not work with the cgi version of PHP, so if your hosting allows you will need to switch to PHP as Apache module or look for an alternative solution.