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

Get Learning PHP, MySQL, and JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.