How can I use Basic HTTP Authentication in PHP?
How is PHP being run? If it's through Apache mod_cgi, I'm afraid you cannot get hold of the authentication information at all. Apache won't pass it to CGI apps unless you compile it with the SECURITY_HOLE_PASS_AUTHORIZATION
flag. (Whether it's actually a security hole or not depends on whether other users on your server have a lower or greater privilege than your website users.)
If it's IIS CGI, you have to ensure that only ‘Anonymous’ directory access is configured, or IIS will try to step in and authenticate credentials itself.
echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
HTML-injection security hole (well, if it worked). Use htmlspecialchars()
. Man, is that PHP doc page full of highly questionable advice and code.
You can try to look at $_SERVER['HTTP_AUTHORIZATION']
as well, though I suspect it's the mod_cgi issue in which case neither variable will be present and you will have to resort to cookie-based login instead. Or change to a host with a more modern approach to PHP hosting, such as FastCGI or mod_php.
Try this::
<?php
/*
** Define a couple of functions for
** starting and ending an HTML document
*/
function startPage()
{
print("<html>\n");
print("<head>\n");
print("<title>Listing 24-1</title>\n");
print("</head>\n");
print("<body>\n");
}
function endPage()
{
print("</body>\n");
print("</html>\n");
}
/*
** test for username/password
*/
if( ( isset($_SERVER['PHP_AUTH_USER'] ) && ( $_SERVER['PHP_AUTH_USER'] == "leon" ) ) AND
( isset($_SERVER['PHP_AUTH_PW'] ) && ( $_SERVER['PHP_AUTH_PW'] == "secret" )) )
{
startPage();
print("You have logged in successfully!<br>\n");
endPage();
}
else
{
//Send headers to cause a browser to request
//username and password from user
header("WWW-Authenticate: " .
"Basic realm=\"Leon's Protected Area\"");
header("HTTP/1.0 401 Unauthorized");
//Show failure text, which browsers usually
//show only after several failed attempts
print("This page is protected by HTTP " .
"Authentication.<br>\nUse <b>leon</b> " .
"for the username, and <b>secret</b> " .
"for the password.<br>\n");
}
?>
For PHP-CGI:
in .htaccess add this:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
</IfModule>
and at the beginning of your script add this:
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':' , base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
I think the PHP methods rely on Basic Authentication being configured on the Web Server. An easy way to do this is to include a .htaccess file in the directory you want to enable basic authentication for.
Most unix-based web hosts allow you to do this by just uploading this file. A separate file (call this .htauth) will hold the user logins that are allowed to access the site or directory.