PHP

HTTP Authentication with PHP

PHP can access the credentials collected using the HTTP mechanisms introduced in the last section, and can actually manage the HTTP authentication without relying on Apache's configuration.

Access to User Credentials from PHP

PHP provides access to the encoded credentials from the HTTP Authorized header field through the global variables $PHP_AUTH_USER, $PHP_AUTH_PW, and $PHP_AUTH_TYPE. PHP initializes the variable $PHP_AUTH_USER with the username and $PHP_AUTH_PW with the password entered into the browser authentication dialog box. The global variable $PHP_AUTH_TYPE is initialized with the encoding type used by the browser; typically this value is set to Basic.

The script shown in Example 9-3 reads the authentication global variables and displays them in the body of the response. For the PHP code in Example 9-3 to display the authentication credentials, the script needs to be requested after a user has been challenged for a username and password. This happens if the file containing the script is placed within a directory configured by Apache to require authentication.

Example 9-3. PHP access to authentication
<!DOCTYPE HTML PUBLIC
    "-//W3C//DTD HTML 4.0 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd" >
<html>
  <head><title>Authentication</title></head>
  <body>
    <h2>Hi there <?=$PHP_AUTH_USER?></h2>
    <p>Thank you for your password
                 '<?=$PHP_AUTH_PW?>'!
  </body>
</html>

Applications can use the encoded credentials to support features that rely on identifying the user. For example, an application that charges on a per-page view basis might use the $PHP_AUTH_USER variable when recording an access to a particular page. In this way, Apache can provide the authentication, and the application records the users' usage. While this approach removes the need to write any PHP code to implement authentication, users and passwords need to be maintained in an Apache password file. In the next section we describe how to manage HTTP authentication from within a PHP script, thus relieving Apache of authentication responsibilities and allowing different logic to be applied to the authorization of requests.

by BrainBellupdated
Advertisement: