dan forys


HTTP authentication in PHP

Posted on 2007-06-12 - Comments

I’ve just discovered, totally by accident, how to get HTTP Authentication (when the browser pops up a dialog asking for the username and password – usually set with a .htaccess file) values within PHP. Previously, I’d just assumed that the authentication was a “black box” and I was unable to use it within my scripts. I had done some experimentation to see if any of the i nformation was present in the _POST or _COOKIE arrays to no avail.

At work, we were using some software which, somewhat curiously, seemed to automatically log users in without them supplying the correct credentials. After much digging, inserting debug messages and experimentation, I found that PHP had the authentication values in the superglobal $_REQUEST array. The values you can use are as follows:

// Superglobal showing the username supplied

// Superglobal showing the password
print $_SERVER['PHP_AUTH_PW'];

// Authentication type (Basic or digest in PHP5)
print $_SERVER['AUTH_TYPE'];

This is immensely useful for me, because it opens all sorts of possibilities for single sign-on style systems. It also means I can work with non PHP files, without having to authenticate twice or rely on PHP sessions alone.

Of course, perhaps I should have looked at the PHP manual on HTTP authentication first!