HTTP Authentication on PHP as CGI (like Dreamhost)

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:

  1. <IfModule mod_rewrite.c>
  2. RewriteEngine on
  3. RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]
  4. </IfModule>

This will pass authorization tokens into an environment variable named REMOTE_USER.

Then, the PHP script:

  1. <?php
  2. // Split the user/pass variable
  3. list($_SERVER&#91;'PHP_AUTH_USER'&#93;, $_SERVER&#91;'PHP_AUTH_PW'&#93;) =
  4.     explode(':' , base64_decode(substr($_SERVER&#91;'REDIRECT_REMOTE_USER'&#93;, 6)));
  5.  
  6.  
  7. // Open a user/pass prompt if needed
  8. if (!$_SERVER&#91;'PHP_AUTH_USER'&#93;) {
  9.     header('WWW-Authenticate: Basic realm="My Realm"');
  10.     header('HTTP/1.0 401 Unauthorized');
  11.     echo 'You cannot see this, sorry.'; // in case they hit "Cancel"
  12.     exit;
  13.  
  14. // or deal with the login/password (like, check them, obviously)
  15. } else {
  16.     echo "<p>Hello, </p>".$_SERVER['PHP_AUTH_USER'];
  17.     echo "<p>You entered as your password: </p>".$_SERVER['PHP_AUTH_PW'];
  18. }
  19. ?>

This is labeled as "WORKSFORME" on Dreamhost's PHP as CGI (PHP Version 5.2.6, for the record).

3 comments

  1. Joseph Scott

    Note that this isn't specific to PHP as a CGI under Apache. Apache does not pass HTTP Basic Authentication information to any CGIs.

  2. Thomas Urban

    Thank you for this simple solution.

  3. Torleif

    You use E=REMOTE_USER in your htaccess, and $_SERVER['REDIRECT_REMOTE_USER'] in your PHP. Is that intentional, or should one be changed to the other so they match?

Comments are closed.