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?
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With