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 ...
Get Web Database Applications with PHP, and MySQL 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.