Using Apache to Authenticate

The simplest method to restrict access to an application is to use the Apache authentication support. The Apache server can easily be configured to use HTTP authentication to protect the resources it serves. Apache allows authentication to be set up on a directory-by-directory basis by adding parameters to the Directory setting in the httpd.conf configuration file. The following example shows part of an httpd.conf file that protects the resources-HTML files, PHP scripts, images, and so on-stored in the /usr/local/apache/htdocs/auth directory:

# Set up an authenticated directory
<Directory "/usr/local/apache/htdocs/auth">
  AuthType Basic
  AuthName "Secret Mens Business"
  AuthUserFile /usr/local/apache/allow.users
  require Alexa, dave, jim

If PHP scripts and other sensitive resources are placed within a protected directory, a user can access the application only by first passing the Apache authentication. The Apache server responds with a challenge to unauthorized requests for any resources in the protected directory. The AuthType is set to Basic to indicate the method that encodes the username and password collected from the browser, and the AuthName is set to the name of the realm. Apache authorizes users who are listed in the require setting by checking the username and password against those held in the AuthUserFile. There are other parameters that aren't discussed here; you should refer to the Apache references listed in Appendix E for full configuration details.

For simple web database applications, Apache authentication provides a suitable solution. When usernames and passwords need to be checked against a database or some other source, or when HTTP authentication can't meet the needs of the application, authentication can be managed by PHP. The next section describes how PHP can manage HTTP authentication directly without configuring Apache. Later, in Section 9.4, we describe how to provide authentication without using HTTP authentication support.