In: , ,
On: 2009 / 04 / 29 Viewed: 56505 times
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:

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

PHP:
  1. <?php
  2. // Split the user/pass variable
  3. list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
  4.     explode(':' , base64_decode(substr($_SERVER['REDIRECT_REMOTE_USER'], 6)));
  5.  
  6.  
  7. // Open a user/pass prompt if needed
  8. if (!$_SERVER['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.

2 Blablas

  1. 1
    Joseph Scott United States »
    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.

  2. 2
    Thomas Urban Germany »
    thought, on 08/Nov/09 at 12:06 pm # :

    Thank you for this simple solution.

Leave a Reply

Comment Guidelines or Die

  • HTML: You can use these tags: <a href=""> <em> <i> <b> <strong> <blockquote>
  • Posting code: Post raw code (no <> &lt; etc) within appropriate tags : [php][/php], [css][/css], [html][/html], [js][/js], [sql][/sql], [xml][/xml], or generic [code][code]
  • Gravatars: Curious about the little images next to each commenter's name ? Go to Gravatar.
  • Spam: Various spam plugins on patrol. I'll put pins in a Voodoo doll if you spam me.
  • I will mark as Spam test comments, all comments with SEO names (ie "My Cool Online Shop" instead of "Joe") or containing forum-like signatures.

Read more ?