I'm writing a very simple authorization script that just uses a PHP header to prevent non-admins from accessing other sites. This PHP script is just called authorize.php and is included in other files via
<?php require_once('authorize.php'); ?>
before the remaining HTML code.
Here's the script:
<?php
//User name and password for authentication
$username = 'rock';
$password = 'roll';
//these arent the real passwords of course...
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || ($_SERVER['PHP_AUTH_USER'] != $username) || ($_SERVER['PHP_AUTH_PW'] != $password)) {
//The user name/password are incorrect so send the authentication headers
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm= "Guitar Wars" ');
exit('<h2>Guitar Wars</h2>Sorry, but you do not have permission to view this page');
}
?>
And that's it. It's not fancy at all, but for some reason entering the user/pw correctly simply causes the AUTH box to pop up again every time.
I sniffed around for an answer, and although I found some similar problems, none really solved it. For example: this but my headers ARE in the if statement... or this one in which the question wasn't really answered... I even tried entering this..
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
into the .htaccess of the root directory based on something else I found, but that didn't help and I honestly don't even know what it does...
I did check my php info, looks like its CGI/fastCGI.
What is wrong here? I've pretty much copied the code verbatum out of the textbook I'm learning from (I'm an English professor, not a programmer mind you so please be gentle with me)
I found an answer to my problem after 2 days of searching... My above idea of editing the .htaccess file was only partially right. I needed to include this in the .htaccess file
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
</IfModule>
and then in my PHP script, above where I made the headers, include this:
if(preg_match('/Basic+(.*)$/i', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $matches))
{
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':' , base64_decode(substr($_SERVER['REDIRECT_HTTP_AUTHORIZATION'], 6)));
}
I'm just a beginner so I have absolutely no clue what any of that does, but hey, it fixed the problem. If others are having this issue, allow me to elaborate on some other things I noticed so you can compare your situation to mine.