O'Reilly logo

Learning PHP, MySQL, and JavaScript by Robin Nixon

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

HTTP Authentication

HTTP authentication uses the web server to manage users and passwords for the application. It’s adequate for most applications that ask users to log in, although some applications have specialized needs or more stringent security requirements that call for other techniques.

To use HTTP authentication, PHP sends a header request asking to start an authentication dialog with the browser. The server must have this feature turned on in order for it to work, but because it’s so common, your server is very likely to offer the feature.

Note

Although it is usually installed with Apache, HTTP authentication may not necessarily be installed on the server you use. So attempting to run these examples may generate an error telling you that the feature is not enabled, in which case you must install the module, change the configuration file to load the module, or ask your system administrator to do these fixes.

From the user’s point of view, when they enter your URL into the browser or visit via a link, an “Authentication Required” prompt pops up requesting two fields: username and password (see Figure 13-2 for how this looks in Firefox).

An HTTP authentication login prompt

Figure 13-2. An HTTP authentication login prompt

The code to make this happen looks like Example 13-1.

Example 13-1. PHP authentication

<?php if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) { echo "Welcome User: " . $_SERVER['PHP_AUTH_USER'] ...

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