Back to Programming Articles

Getting HTTP Authorization to work with PHP CGI mode
by TECK 08 Oct 2006

This tutorial is vBulletin.org and cPublisher.com copywrited. All rights reserved.
Please ask permission in this thread to copy the tutorial. If granted, post a link that points to this page.


As you all know, using PHP-CGI is more secure then the ole Apache module flavour.
However, with PHP-CGI you cannot use anymore real user authentification, based on a .htaccess/.htpasswd file.

The fix is really easy (and secure), all you need is to have Apache mod_rewrite enabled.

Create a .htaccess file, with the content:
Code:
RewriteEngine On
... your RewriteCond/RewriteRules here ...
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]
Make sure the line above is the last one in your .htaccess file, if you already have one in place.
Then, in your PHP file, use:
PHP Code:
<?php

$auth 
base64_decode(substr($_SERVER['REMOTE_USER'], 6));
if (
strlen($auth) > OR strcasecmp($auth':') > 0)
{
    list(
$name$password) = explode(':'$auth);
    
$_SERVER['PHP_AUTH_USER'] = $name;
    
$_SERVER['PHP_AUTH_PW'] = $password;

    
$user_authorized true;
}
else
{
    
header('WWW-Authenticate: Basic realm="My Realm"');
    
header('HTTP/1.0 401 Unauthorized');
    echo 
'Go away!';
}

if (
$user_authorized)
{
    
// do your thing here ...
}

?>
I needed this for the apc.php file, running on my server PHP 5.1.6 with FastCGI mode enabled.
For those who want to fix the apc.php file, find:
PHP Code:
// authentication needed?
//
if (!USE_AUTHENTICATION) {
    
$AUTHENTICATED=1;
} else {
    
$AUTHENTICATED=0;
    if (
ADMIN_PASSWORD!='password' && ($MYREQUEST['LO'] == || isset($_SERVER['PHP_AUTH_USER']))) { 
Replace with:
PHP Code:
// authentication needed?
//
if (!USE_AUTHENTICATION)
{
    
$AUTHENTICATED 1;
}
else
{
    
$auth base64_decode(substr($_SERVER['REMOTE_USER'], 6));
    if (
strlen($auth) > OR strcasecmp($auth':') > 0)
    {
        list(
$name$password) = explode(':'$auth);
        
$_SERVER['PHP_AUTH_USER'] = $name;
        
$_SERVER['PHP_AUTH_PW'] = $password;
    }

    
$AUTHENTICATED 0;
    if (
ADMIN_PASSWORD!='password' && ($MYREQUEST['LO'] == || isset($_SERVER['PHP_AUTH_USER']))) { 

vblts.ru supports vBulletin®, 2022-2024