HTTP Authentication with PHP running as CGI
While developing a project using two factor authentication, with a key fob, I needed to use HTTP Basic Authentication over SSL, to prevent XSS as the project was a web based proxy. Now I had PHP5 running as a module, but PHP4 as CGI. There was the problem HTTP Authentication isn’t available under PHP running as CGI.
First you need to configure mod_rewrite:
.htaccess:
RewriteEngine on
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
What that will do is feed the base64′d user:pass into an environment variable named HTTP_AUTHORIZATION.
Then just add this above your script:
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(’:’ , base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
That splits up the username and password, and makes it look as if you were running PHP as a module.
So for a sample script:
// split the user/pass parts
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(’:', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
// open a user/pass prompt
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header(’WWW-Authenticate: Basic realm=”My Realm”‘);
header(’HTTP/1.0 401 Unauthorized’);
echo ‘Text to send if user hits Cancel button’;
exit;
} else {
echo ‘Hello, ‘.htmlentities($_SERVER['PHP_AUTH_USER']).’
‘;
echo ‘You entered as your password: ‘.htmlentities($_SERVER['PHP_AUTH_PW']).’
‘;
}
?>
Steven
jan said,
January 29, 2007 @ 8:23 pm
Thanks dude, it worked!
Alex said,
June 28, 2007 @ 4:34 pm
You saved me from dispair. Amazing mod_rewrite trickery, well done.
Asbjørn Ulsberg said,
December 3, 2007 @ 11:37 pm
This didn’t work for me. I’ve set up authentication in .htaccess and get the username/password challenge, but when I reach the little auth.php script I’ve created, it just says “Hello,You entered as your password:”; clearly the authentication information didn’t drip through from Apache to PHP.
Just echoing the $_SERVER['HTTP_AUTHORIZATION']; variable yields null too, so the .htaccess hack is clearly not working. Any idea why it isn’t and what I can do to make it work? Do I need to turn on a magic switch for the [E] httpd directive to work, for instance?
Gary said,
March 4, 2008 @ 11:33 pm
Phew! You saved me lots of hassle :-)
The only problem I had was that $_SERVER[’HTTP_AUTHORIZATION’] didn’t exist, however $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] did (discovered with the aid of “print_r($_SERVER);”), so I did a swap and then the base64 decode worked a treat.
Thank you!