O'Reilly logo

Learning PHP and MySQL by Jon A. Phillips, Michele E. Davis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

PHP and HTTP Authentication

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.

The prompt for authentication to the Member Area realm

Figure 13-2. The prompt for authentication to the Member Area realm

If the user clicks Cancel, he'll see Figure 13-3.

Clicking Cancel causes a message that the user must log in

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required