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

    "-//W3C//DTD HTML 4.0 Transitional//EN"
    "" >
    <h2>Hi there <?=$PHP_AUTH_USER?></h2>

    <p>Thank you for your password


Applications can use the encoded credentials to support features that rely on identifying ...

Get Web Database Applications with PHP, and MySQL now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.