Skip to content
Advertisement

How can I use Basic HTTP Authentication in PHP?

I’m trying to use Basic HTTP Authentication and followed the example on the PHP manual page. But it doesn’t work for me. The variable $_SERVER['PHP_AUTH_USER'] doesn’t seem to be set. When a user try to log in, the user is prompted whith a new login-dialog. The server is running PHP 5.3.3 and I have tried with Google Chrome and Internet Explorer.

Here is the simple example that I used:

<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="Jonas Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'User pressed Cancel';
    exit;
} else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as you password.</p>";
}
?>

What is wrong? How can I use Basic HTTP Authentication in PHP?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement