PHP can use authentication from the Apache web server. PHP sends a header request to the browser requesting an authentication dialog on the client's browser. You'll recognize this prompt as a standard browser login prompt. Because the authentication head must come before any other HTML output, this works only with the module-based PHP installation, not the CGI version.
Example 13-4 shows how to use HTTP authentication.
Example 13-4. Using HTTP authentication with a PHP script
<?php if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) { header('WWW-Authenticate: Basic realm="Member Area"'); header("HTTP/1.0 401 Unauthorized"); echo "Please login with a valid username and password."; exit; } else { echo "You entered a username of: ".$_SERVER['PHP_AUTH_USER']." "; echo "and a password of: ".$_SERVER['PHP_AUTH_PW']."."; } ?>
The code from Example 13-4 displays a prompt like the one in Figure 13-2.
Figure 13-2. The prompt for authentication to the Member Area realm
If the user clicks Cancel, he'll see Figure 13-3.
Figure 13-3. Clicking Cancel causes a message that the user must log in
That's a fairly simple example. We checked to see if the username and password were set, then displayed them to the user. The realm
field provides a way for grouping ...
No credit card required