Please answer this simple SPAM challenge: min(zero, eight)?
(Example: nine)

The Note You're Voting On

blah at blah dot com
12 years ago
Getting PHP Authentication to work with CGI-bin.

You must have mod_rewrite installed for this to work. In the directory (of the file) you want to protect, for the .htaccess file:

# PHP (CGI mode) HTTP Authorization with ModRewrite:
# most right example with header check for non empty:
RewriteEngine on
RewriteCond %{HTTP:Authorization}  !^$
RewriteRule ^test.php$ test.php?login=%{HTTP:Authorization}

Change the Rewrite rule to whatever you want it to be. For simplicity, this example only applies to one file, test.php and only if the HTTP Authorization needs to take place.

In the php file:
if (isset($_GET['login'])) {
    $d = base64_decode( substr($_GET['login'],6) );
    list($name, $password) = explode(':', $d);
    echo 'Name:' . $name . "<br>\n";
    echo 'Password:' . $password . "<br>\n";
} else {
   header('WWW-Authenticate: Basic realm="My Realm"');
   header('HTTP/1.0 401 Unauthorized');
   echo 'You are not authorized. Bad user, bad!';

You need to get rid of the first 6 characters for some reason, then decode the Auth data from its base64 format. Then it's a simple matter of extracting the data. You can even pass the data to the $_SERVER variables $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW']. These are the variables that get the login data if you have PHP running as an Apache module. This is useful for mods or plugins.

<< Back to user notes page

To Top