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. If when you attempt to run these examples, you see an error message telling you that the feature is not enabled, you must install the module, change the configuration file to load the module, or ask your system administrator to do these fixes.

From the users’ 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: User Name and Password (see Figure 12-2 for how this looks in Firefox).

An HTTP authentication login prompt
Figure 12-2. An HTTP authentication login prompt

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

Example 12-1. PHP authentication
<?php if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) { echo "Welcome User: ...

Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition 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.