Basic HTTP authentication uses a challenge/response scheme to authenticate users attempting to access a password-protected page. The challenge process begins when the user requests a file from a Web server. If the file is within a protected area, the server responds by sending out a 401 (unauthorized user) string in the header of the response. The browser detects that response and up pops the username/password dialog box. The user enters a username and password in the dialog box, then clicks OK to send the information back to the server for authentication.
If the username and password pair is valid, the protected file will be displayed to the user. The validation will carry through for as long as the now-authenticated user is within the protected area. However, if the username and password typed into the dialog box cannot be authenticated, the dialog box will again be displayed, prompting the user to try again. This cycle will be repeated until the proper username/password combination is entered or the user gives up and slinks away.
A simple PHP script can mimic the HTTP authentication challenge/response system by sending the appropriate HTTP headers that cause the automatic display of the username/password dialog box. PHP stores the information entered in the dialog box in three global variables ($PHP_AUTH_USER,
$PHP_AUTH_PW, and $PHP_AUTH_TYPE). Using these variables, you can validate input against a username/password list kept in a text file, database, or any other list you have lying about.
NOTE: The $PHP_AUTH_USER, $PHP_AUTH_PW, and $PHP_AUTH_TYPE global variables are available only when PHP is installed as a module. If you're using the CGI version of PHP, you're limited to .htaccess-based authentication or database-driven authentication using HTML forms to input the username and password and PHP to validate matches.
Let's start slowly, by writing a PHP script that simply checks for a value (any value) for $PHP_AUTH_USER. If no value exists, the script will send a 401 Unauthorized message in the header. This header will cause the username/password dialog box to appear, and execution of the script will halt. After the user enters some values in the dialog box and presses the OK button, the values will be sent and the page will reload. When a value like $PHP_AUTH_USER is entered, the first section of the script will be skipped and the header information will not be sent. Just to prove that I'm not lying to you, the remainder of the script prints the values entered for $PHP_AUTH_USER and $PHP_AUTH_PW. Give it a shot and see how it works.