I am a bit new to php coding. And i am trying to get through af chapter in a book covering the topic HTTP Authentication.
But when I run this code on my localhost WAMP server, the box just keeps popping up again, even though I have filled the forms properly.
<?php
$username = 'admin';
$password = 'letmein';
if (isset($_SERVER['PHP_AUTH_USER']) &&
isset($_SERVER['PHP_AUTH_PW']))
{
if ($_SERVER['PHP_AUTH_USER'] == $username &&
$_SERVER['PHP_AUTH_PW'] == $password)
echo "You are now logged in";
else die("Invalid username / password combination");
}
else
{
header('WWW-Authenticate: Basic realm="Restricted Section');
header('HTTP/1.0 401 Unauthorized');
die ("Please enter your username and password");
}
?>
So what should I do to make the browser accept my answer?
There is a hint in the book:
The security in modern browsers is getting stricter and has reached a point where you may not easily be able to test HTTP authentication on a local filesystem unless you alter your browser’s settings. This is to protect you from potentially malicious files you may download from the Internet (since local files generally pose greater security risks). Instead, if you wish to write code that uses this type of authentication, this is one instance where you may prefer to perform your testing on a remote server using an Internet connection.
So how do I test my php scripts on a remote server? Or can I alter my own settings to allow me to use this feature?
That statement is nonsense; as long as you access the file using a web server and URL like http://localhost/...
and not file:///...
, there's no significant difference. You don't need a "remote" server to write code.
The problem in this case is likely that the web server feels responsible for handling the authentication and your PHP script is not even involved at all. You can confirm this by changing the realm
value and see if it has any effect in the browser popup.
Otherwise, var_dump($_SERVER)
to confirm the values you're receiving.