Example 16-2. HTTP Authentication example
forcing a new name/password
<?php
function authenticate() {
header('WWW-Authenticate: Basic realm="Test Authentication
System"');
header('HTTP/1.0 401 Unauthorized');
echo "You must enter a valid login ID and password
to access this resource\n";
exit;
}
if (!isset($_SERVER['PHP_AUTH_USER']) ||
($_POST['SeenBefore'] == 1 && $_POST['OldAuth']
== $_SERVER['PHP_AUTH_USER'])) {
authenticate();
}
else {
echo "<p>Welcome: {$_SERVER['PHP_AUTH_USER']}<br
/>";
echo "Old: {$_REQUEST['OldAuth']}";
echo "<form action='{$_SERVER['PHP_SELF']}' METHOD='post'>\n";
echo "<input type='hidden' name='SeenBefore' value='1'
/>\n";
echo "<input type='hidden' name='OldAuth' value='{$_SERVER['PHP_AUTH_USER']}'
/>\n";
echo "<input type='submit' value='Re Authenticate'
/>\n";
echo "</form></p>\n";
}
?>
This behavior is not required by the HTTP Basic authentication
standard, so you should never depend on this. Testing with
Lynx has shown that Lynx does not clear the authentication
credentials with a 401 server response, so pressing back
and then forward again will open the resource as long as
the credential requirements haven't changed. The user can
press the '_' key to clear their authentication information,
however.
Also note that until PHP 4.3.3, HTTP Authentication did
not work using Microsoft's IIS server with the CGI version
of PHP due to a limitation of IIS. In order to get it to
work in PHP 4.3.3+, you must edit your IIS configuration
"Directory Security". Click on "Edit"
and only check "Anonymous Access", all other fields
should be left unchecked.
Another limitation is if you're using the IIS module (ISAPI),
you may not use the PHP_AUTH_* variables but instead, the
variable HTTP_AUTHORIZATION is available. For example, consider
the following code: list($user, $pw) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'],
6)));
IIS Note:: For HTTP Authentication to work with IIS, the
PHP directive cgi.rfc2616_headers must be set to 0 (the
default value).
Note: If safe mode is enabled, the uid of the script is
added to the realm part of the WWW-Authenticate header.