In: , ,
On: 2009 / 04 / 29
Shorter URL for this post: http://ozh.in/kk

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'], $_SERVER['PHP_AUTH_PW']) =
  4.     explode(':' , base64_decode(substr($_SERVER&#91;'REDIRECT_REMOTE_USER'], 6)));
  5.  
  6.  
  7. // Open a user/pass prompt if needed
  8. if (!$_SERVER&#91;'PHP_AUTH_USER']) {
  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).

Shorter URL

Want to share or tweet this post? Please use this short URL: http://ozh.in/kk

Metastuff

This entry "HTTP Authentication on PHP as CGI (like Dreamhost)" was posted on 29/04/2009 at 12:01 pm and is tagged with , ,
Watch this discussion : Comments RSS 2.0.

3 Blablas

  1. Joseph Scott says:

    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 says:

    Thank you for this simple solution.

  3. Torleif says:

    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?

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
Gravatars: Curious about the little images next to each commenter's name ? Go to Gravatar and sign for a free account
Spam: Various spam plugins may be activated. I'll put pins in a Voodoo doll if you spam me.

Read more ?