Tuesday, February 16, 2010

How to make HTTP Auth work with PHP CGI

From PHP manual:
The HTTP Authentication hooks in PHP are only available when it is running as an Apache module and is hence not available in the CGI version. In an Apache module PHP script, it is possible to use the header() function to send an "Authentication Required" message to the client browser causing it to pop up a Username/Password input window. Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the predefined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE set to the user name, password and authentication type respectively. These predefined variables are found in the $_SERVER and $HTTP_SERVER_VARS arrays. Both "Basic" and "Digest" (since PHP 5.1.0) authentication methods are supported. See the header() function for more information.
Here is a fix:
  1. Upload a .htaccess file with the following content:
    <IfModule mod_rewrite.c>
         RewriteEngine on
         RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
    </IfModule>


  2. Upload a test file with the following php code to verify that HTTP AUTH is working:
    <?php
    if (!isset($_SERVER['PHP_AUTH_USER'])) {
       header('WWW-Authenticate: Basic realm="For testing only"');
       header('HTTP/1.0 401 Unauthorized');
       die ('Sorry, you have to login to view this page');
     } else {
       echo "You enered, Username: ".$_SERVER['PHP_AUTH_USER']." and password: ". $_SERVER['PHP_AUTH_PW']." " };
    ?>
  3. Similar code can be used in cases where HTTP auth validation is required.

Note: Web Hosts like Dreamhost and Godaddy (Linux Shared Hosting) use PHP CGI. In such cases, this fix solves the following error:

401 Unauthorized

This server could not verify that you are authorized to access the document requested. Either you supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required.

Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.

No comments:

Post a Comment