Using PHP's HTTP Authentication is a simple way to protect scripts behind a login/password prompt. There's one little problem: it's supposed to work only on PHP as an Apache module, not the CGI version. It took me a while, hair pulling and some googling to get a basic HTTP Auth system working on Dreamhost's PHP as CGI so for my own future reference, and for anyone that would find it useful, here's the trick.
First, you need a little .htaccess twist:
-
<IfModule mod_rewrite.c>
-
RewriteEngine on
-
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]
-
</IfModule>
This will pass authorization tokens into an environment variable named REMOTE_USER.
Then, the PHP script:
-
<?php
-
// Split the user/pass variable
-
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
-
explode(':' , base64_decode(substr($_SERVER['REDIRECT_REMOTE_USER'], 6)));
-
-
-
// Open a user/pass prompt if needed
-
if (!$_SERVER['PHP_AUTH_USER']) {
-
header('WWW-Authenticate: Basic realm="My Realm"');
-
header('HTTP/1.0 401 Unauthorized');
-
echo 'You cannot see this, sorry.'; // in case they hit "Cancel"
-
exit;
-
-
// or deal with the login/password (like, check them, obviously)
-
} else {
-
echo "<p>Hello, </p>".$_SERVER['PHP_AUTH_USER'];
-
echo "<p>You entered as your password: </p>".$_SERVER['PHP_AUTH_PW'];
-
}
-
?>
This is labeled as "WORKSFORME" on Dreamhost's PHP as CGI (PHP Version 5.2.6, for the record).
Shorter URL
Want to share or tweet this post? Please use this short URL: http://ozh.in/kk

said, on 29/Apr/09 at 6:08 pm # :
Note that this isn't specific to PHP as a CGI under Apache. Apache does not pass HTTP Basic Authentication information to any CGIs.
thought, on 08/Nov/09 at 12:06 pm # :
Thank you for this simple solution.