What is HTTP Authentication?
You may not consciously know what HTTP Authentication is; however, it is most likely that you have used it once or twice, if not many of times. It is used commonly as login interfaces to the administration areas of some PHP scripts, as well as some popular websites, such as vBulletin.com. To refresh your memory, here is a small image of the login process:
Here's the code:
HTTP Authenticationif (@$_SERVER['PHP_AUTH_USER'] != 'john' && @$_SERVER['PHP_AUTH_PW'] != 'secret') {
header('WWW-Authenticate: Basic realm="Site Administration Area"');
header('Status: 401 Unauthorized');
/* Special Header for CGI mode */
header('HTTP-Status: 401 Unauthorized');
?>
Access Unauthorized
Access to the requested page denied
You have been denied access to this page for entering an
incorrect or non-exist username and password.
Press 'Refresh' to retry the login procedure.
exit;
}
echo 'Welcome to our site, username ' . $_SERVER['PHP_AUTH_USER'];
?>
This code contains all the important aspects of HTTP authentication that you need to get started. First thing to notice is that there is no output before header() calls. Secondly, notice that we have two special variables inside the$_SERVER superglobal. These are PHP_AUTH_USER and PHP_AUTH_PW and they represent the current HTTP authenticated username and password. As they may not exist when we call our script, I have placed an 'at' symbol (@) before both of these variables. The @ symbol tells PHP to suppress any errors that may arise in the specified statement. Hence, we know that an error might occur because these variables may not yet exist, so we use @ to suppress it.