HTTP Authentication with PHP running as CGI/SuExec

Here it is a tricky one. PHP is a feature-rich programming language and they even have a simple HTTP Auhtentication included.

The bad news is that this type of Authorization does not work when your PHP is installed and working as CGI. It works perfectly when PHP is installed as a module though.

However, there is a workaround available which can make HTTP Auth for PHP working even when in CGI mode.

First you need to create the following .htaccess file:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule .* – [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]

The lines above will assign the username/pass pairs to an environment variable named HTTP_AUTHORIZATION.


Then in your PHP script you should add the following, right before your user/pass check routine:

list($_SERVER[‘PHP_AUTH_USER’], $_SERVER[‘PHP_AUTH_PW’]) = explode(‘:’ , base64_decode(substr($_SERVER[‘HTTP_AUTHORIZATION’], 6)));

So here it is how a sample PHP script using HTTP Authentication would look like:

// split the user/pass parts
list($_SERVER[‘PHP_AUTH_USER’], $_SERVER[‘PHP_AUTH_PW’]) = explode(‘:’, base64_decode(substr($_SERVER[‘HTTP_AUTHORIZATION’], 6)));

// open a user/pass prompt
if (!isset($_SERVER[‘PHP_AUTH_USER’])) {
header(‘WWW-Authenticate: Basic realm=»My Realm»‘);
header(‘HTTP/1.0 401 Unauthorized’);
echo ‘Text to send if user hits Cancel button’;
} else {
echo «<p>Hello, </p>».$_SERVER[‘PHP_AUTH_USER’];
echo «<p>You entered as your password: </p>».$_SERVER[‘PHP_AUTH_PW’];