Ratings, reviews, plans and features to help you find the right web hosting provider for your site.

HTTP Authentication with PHP running as CGI/SuExec

Web Hosting Articles » A simple guide to .htaccess » 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 authentication is similar to the Apache one explained here

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]
</IfModule>

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:

<?php
// 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';
   exit;
 } else {
   echo "<p>Hello, </p>".$_SERVER['PHP_AUTH_USER'];
   echo "<p>You entered as your password: </p>".$_SERVER['PHP_AUTH_PW'];
 }
?>

  1. How to block users from accessing your site based on their IP address
  2. How to prevent or allow directory listing?
  3. How to change the error documents – 404 Page Not Found, etc
  4. Using .htaccess for password protecting your folders
  5. Using .htaccess to block referrer spam
  6. Disable Hot-Linking of images and other files
  7. Redirect URLs using .htaccess
  8. Introduction to mod_rewrite and some basic examples
  9. Force SSL/https using .htaccess and mod_rewrite
  10. 301 Permanent redirects for parked domain names
  11. Enable CGI, SSI with .htaccess
  12. How to add Mime-Types using .htaccess
  13. Change default directory page
  14. Block Bad robots, spiders, crawlers and harvesters
  15. Make PHP to work in your HTML files with .htacess
  16. Change PHP variables using .htaccess
  17. HTTP Authentication with PHP running as CGI/SuExec
  18. Force www vs non-www to avoid duplicate content on Google
  19. Duplicate content fix index.html vs / (slash only)

Comments 48 >>

laxen Said,
Aug 23, 2006 @ 08:57

This doesn't work for me.
To get it working for me I added this in .htaccess. (Change test.php to your script name)
[code]
RewriteEngine on
RewriteCond %{HTTP:Authorization} !^$
RewriteRule^test.php$ test.php?login=%{HTTP:Authorization}
[/code]
And then in your PHP script you should add the following, right before your user/pass check routine:
[code]
$d = base64_decode(substr($_GET['login'],6) );
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', $d);
[/code]
misha Said,
Nov 01, 2006 @ 17:36

I've been searching for a solution on this for sometime....and finally i got it !

I've tested the firt method and worked very fine for me.
I have a PHP as CGI and the HTTP Authentication is working.
Reid Said,
Nov 04, 2006 @ 16:56

Thanks, this helped me out!
Alexey Said,
May 25, 2007 @ 02:14

Thanks a million!
Hilary Said,
Aug 17, 2007 @ 06:32

Brilliant - thanks for this. Just one thing I had to change to get it working:

if ($_SERVER['PHP_AUTH_USER']=="")

instead of

if (!isset($_SERVER['PHP_AUTH_USER']))
Sparx Said,
Jan 13, 2008 @ 08:27

Hey guys, its looks like the first example works only on php4, and not on php5, please note that.
Overseer Said,
Mar 23, 2008 @ 06:30

This does not works with PHP5 as fastCGI :(
vince Said,
Mar 24, 2008 @ 04:28

@Overseer

I just ran a test on PHP5 Fcgi enabled server and it worked there without a problem.

It is possible that your PHP/FCGI configuration is a bit different, hence the problem.

@Sparx
It is working on PHP5 for me
Den Said,
Apr 15, 2008 @ 01:47

For works with PHP5:

[Rewrite rule on .htaccess]
RewriteEngine on
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]

[user:pass on PHP-script]
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['REDIRECT_REMOTE_USER'], 6)));

It's perfectly works with apache2.2+php5.2.5+fastcgi2.4.6
Ispcomm Said,
Jun 11, 2008 @ 04:14

Very nice solution. Works, but depending on your apache version the variable you rewrite can be prepended with 'REDIRECT_'.

That is if you're using HTTP_AUTHORIZATION the real variable in _SERVER becomes REDIRECT_HTTP_AUTHORIZATION.

php4/php5 is OK.
Matthew Said,
Aug 07, 2008 @ 16:29

Hello!

Quick question: since .htaccess rules are enforced for the current dirrectory and all sub-directories, if I wanted to create a set of "environmental constants" so that I am able to access them like so:

$_SERVER["MY_APP_ROOT"], or perhaps $_ENV["MY_APP_ROOT"]

How might I define these within the .htaccess file? The motivation for doing this is so that I do not have to keep including the 'Constants.php' file in all of my scripts. I assume it can be done, since in the above example...

RewriteEngine on
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]

...does just this (or something similiar). Run on PHP5 via CGI, Apache2. Thoughts?
ivan hueso Said,
Oct 07, 2008 @ 11:52

Hi,
This is the solution for make this work on PHP5

On the .htaccess copy this

AddType x-mapp-php5 .php

RewriteEngine on
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]


On the php file copy this

list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['REDIRECT_HTTP_AUTHORIZATION'], 6)));
TONTON RIMKA Said,
Dec 09, 2008 @ 19:10

i ve debian distrib with Ispcp, PHP5 Fastcgi, it's not works !
Kotty Said,
Dec 27, 2008 @ 04:49

@TONTON RIMKA

that is working at ISPCP perfectly:

.htaccess:

RewriteEngine on
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]


at php file:
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':' , base64_decode(substr($_SERVER['REDIRECT_REMOTE_USER'], 6)));
rudyryk Said,
Jan 05, 2009 @ 11:32

Thank you!

That helped me on DreamHost :)
Jeff Said,
Mar 24, 2009 @ 17:53

YES. @Kotty + this post FTW! I was searching ALL over trying to figure out what was going on on my dreamhost.com hosted site with my basic Auth and now this solution from @Kotty did the trick! Thanks SOOO Much
Sébastien Marinier Said,
May 07, 2009 @ 10:57

With Apache 2.2 and PHP 5(cgi mode), i've used

SetEnvIfNoCase Authorization "Basic ([a-z0-9=]+)" REMOTE_AUTHORIZATION=$1

This gives me $_SERVER["REDIRECT_REMOTE_AUTHORIZATION"] as a global var.
I don't know if "REDIRECT_" prefix is due to my configuration/environment. You may try without it.

After, you can use the following code, before user both PHP_AUTH_* vars in a traditionnal way:


if (isset($_SERVER["REDIRECT_REMOTE_AUTHORIZATION"]) && $_SERVER["REDIRECT_REMOTE_AUTHORIZATION"]!=''){
$d = base64_decode($_SERVER["REDIRECT_REMOTE_AUTHORIZATION"]);
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', $d); }
Rob Said,
Oct 07, 2009 @ 09:44

Exactly what I needed for my Webcalendar from k5n to allow remote login! I didn't even need to modify the code...just added the .htaccess file to the webcalendar directory. Thanks!
Dave Diamond Said,
Jan 09, 2010 @ 06:53

Thanks for posting this -- you saved me lots of pain and anguish!!
Kimberly Duong Said,
Apr 28, 2010 @ 06:24

... i have dreamhost and for some reason, these solutions aren't working for me... i get a 500 Internal Server Error... any help on this is much appreciated
jamie Said,
Oct 28, 2010 @ 21:09

Thank you - works like a charm. Working with php5 and libapache2-mod-fcgid, I only needed:

RewriteEngine on
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
Brian Said,
Jan 10, 2011 @ 11:34

Sébastien Marinier's method worked for me on Dreamhost:

To .htaccess add:

SetEnvIfNoCase Authorization "Basic ([a-z0-9=]+)" REMOTE_AUTHORIZATION=$1

To script add:

if (isset($_SERVER["REDIRECT_REMOTE_AUTHORIZATION"]) && $_SERVER["REDIRECT_REMOTE_AUTHORIZATION"]!='') {
$d = base64_decode($_SERVER["REDIRECT_REMOTE_AUTHORIZATION"]);
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', $d);
}

Thanks Sébastien !!
Shashi Said,
Feb 10, 2011 @ 00:47

Thanks a lot for posting this example... googled out a lot and came here, and my problem is solved in minutes... i spent many horrible hours on http authentication and could not get a working solution anywhere.

this helped me breathe well now... Thanks!
Koko Said,
Aug 24, 2011 @ 08:55

Thank you so much! Worked like a charm! I have this problem for ages (in an embedded WEB/PHP server) and now it is solved :-)
technoslab Said,
Aug 31, 2011 @ 16:34

For some weird reason, this doesn't work on one of my web servers and works perfectly on others.
Drey Said,
Oct 18, 2011 @ 09:07

Hi. Tried all ways and still no luck
test script asks for credentials after i enter them and click OK.
any tips?
Luca Said,
Mar 25, 2013 @ 13:37

Hi, i tried using:

RewriteEngine on
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]

on the .htaccess and
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':' , base64_decode(substr($_SERVER['REDIRECT_REMOTE_USER'], 6)));
But it doesnt show the Authentication header.
Stefan Said,
May 27, 2013 @ 04:18

I needed to add this to my /etc/apache2/mods-enabled/fcgid.conf to get it to work:

Passheader Authorization
Alessandro Said,
Jun 03, 2013 @ 10:37

That is great!
Many thanks for solving this issue!
mongolian translator Said,
Apr 04, 2014 @ 08:50

The availability of a website is measured by the percentage of a year in which the website is publicly obtainable moreover accessible through the internet. This is separate than measuring the uptime of a system. Uptime commits to the computer itself being online, nevertheless it does negative grab toward account being able to reach it as in the event of a network outage.
utah web design Said,
Apr 05, 2014 @ 02:11

The host might further give an interface or control panel for managing the wengle server further installing scripts, as well as further modules besides duty applications approve e-mail. Some hosts specialize in unequivocal softwares, which are generally used by larger companies that outsource maze infrastructure.
ortalsoft Said,
Apr 11, 2014 @ 03:13

Thanks.
teaching summary writing Said,
Apr 19, 2014 @ 02:42

First, thank you in advance for any insight or help moving in the right direction.I'm finishing a buildout of an EE 2.7.2 site on Webfaction and have run into a wall trying to get HTTP Authentication to work for one of my templates. Basic HTTP Authentication is not an option because of Webfaction's CGI/SuEXEC environment, and I'm trying to follow the recommendation identified here.
online proxy Said,
May 15, 2014 @ 12:26

Sometimes it is so hard to find good and useful posts out there when doing research. Now I will send it to my colleagues as well. Thank you for being one of them.
www.whichwaytopay.com Said,
Jul 21, 2014 @ 20:44

Your post had offered me with another point of view on this subject. I had limited knowledge that things can work in this manner as well. Thank you for sharing your knowledge.
health insurance quotes Said,
Jul 27, 2014 @ 08:26

This is a terrific article, and I would like more information if you have any. I am fascinated with this topic and your post has been one of the best I have read.
Online stream movies Said,
Aug 12, 2014 @ 06:56

I am so glad ...works perfect and your information really helped me.
discount Said,
Sep 11, 2014 @ 20:23

I am trying to decide on a career move and this has helped me with one aspect. Took me time to read all the comments, I discovered so many interesting things inside your blog especially. Thank you so much!
website Said,
Sep 15, 2014 @ 06:23

I am so satisfied finding this blog and I have to admit that all information stated here is really useful. I hope that you will continue to post such great posts like this one in the future. Thanks a lot again.
superkim89 Said,
Sep 17, 2014 @ 00:33

great article
aussie racing cars Said,
Sep 22, 2014 @ 09:09

A thorough file of HTTP response codes can be present bring into being taking place at this point Wikipedia and on w3.org.
What's beneath is not a complete file except a number of usually seen HTTP response codes seen when put in hard and where viable a number of reasons for seeing them.
Help with coursework Said,
Sep 24, 2014 @ 07:51

It is right, whenever we work PHP as CGI, it creates problem in authorization.
Dermalogica Said,
Sep 26, 2014 @ 12:24

Richard Crenian is President of Redev Properties Ltd. His accomplishments are many and his failures were few. He believes that you cannot be a good lifeguard if you have not seen and saved a drowning and he applies that to good real estate investing.
Assignment help uk Said,
Sep 30, 2014 @ 07:31

I usually face this authorization problem in PHP because I am new in PHP web development
Online Essay Writing Service Said,
Oct 01, 2014 @ 02:33

Problems and their solutions every problem have a solution and I got my solution here.
Dissertation Proposal Said,
Oct 11, 2014 @ 01:16

I am doing lot of work on PHP because I am developer on many sites development on PHP work.
mxf converter Said,
Oct 16, 2014 @ 05:41

I am fascinated with this topic and your post has been one of the best I have read.
Санкт-Петербург Said,
Oct 21, 2014 @ 16:29

Thanks for sharing the post.. parents are worlds best person in each lives of individual..they need or must succeed to sustain needs of the family.
Your comments on this article

(required)

(required but never displayed)



security code



Previous: Change PHP variables using .htaccess