PHP  
downloads | documentation | faq | getting help | | php.net sites | links 
search for in the  
previousCreating and manipulating imagesCookiesnext
Last updated: Tue, 28 May 2002
view this page in Printer friendly version | English | Brazilian Portuguese | Czech | Dutch | French | German | Hungarian | Italian | Japanese | Korean | Polish | Romanian | Russian | Spanish | Turkish

Luku 17. HTTP authentication with PHP

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 variables, $PHP_AUTH_USER, $PHP_AUTH_PW and $PHP_AUTH_TYPE set to the user name, password and authentication type respectively. Only "Basic" authentication is supported at this point. See the header() function for more information.

An example script fragment which would force client authentication on a page would be the following:

Esimerkki 17-1. HTTP Authentication example

<?php
  if (!isset($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\n";
    exit;
  } else {
    echo "<p>Hello $PHP_AUTH_USER.</p>";
    echo "<p>You entered $PHP_AUTH_PW as your password.</p>";
  }
?>

Note: Please be careful when coding the HTTP header lines. In order to guarantee maximum compatibility with all clients, the keyword "Basic" should be written with an uppercase "B", the realm string must be enclosed in double (not single) quotes, and exactly one space should precede the "401" code in the "HTTP/1.0 401" header line.

Instead of simply printing out the $PHP_AUTH_USER and $PHP_AUTH_PW, you would probably want to check the username and password for validity. Perhaps by sending a query to a database, or by looking up the user in a dbm file.

Watch out for buggy Internet Explorer browsers out there. They seem very picky about the order of the headers. Sending the WWW-Authenticate header before the HTTP/1.0 401 header seems to do the trick for now.

In order to prevent someone from writing a script which reveals the password for a page that was authenticated through a traditional external mechanism, the PHP_AUTH variables will not be set if external authentication is enabled for that particular page. In this case, the $REMOTE_USER variable can be used to identify the externally-authenticated user.

Configuration Note: PHP uses the presence of an AuthType directive to determine whether external authentication is in effect. Remember to avoid this directive for the context where you want to use PHP authentication (otherwise each authentication attempt will fail).

Note, however, that the above does not prevent someone who controls a non-authenticated URL from stealing passwords from authenticated URLs on the same server.

Both Netscape Navigator and Internet Explorer will clear the local browser window's authentication cache for the realm upon receiving a server response of 401. This can effectively "log out" a user, forcing them to re-enter their username and password. Some people use this to "time out" logins, or provide a "log-out" button.

Esimerkki 17-2. HTTP Authentication example forcing a new name/password

<?php
  function authenticate() {
    header( "WWW-Authenticate: Basic realm=\"Test Authentication System\"");
    header( "HTTP/1.0 401 Unauthorized");
    echo "You must enter a valid login ID and password to access this resource\n";
    exit;
  }
 
  if (!isset($PHP_AUTH_USER) || ($SeenBefore == 1 && !strcmp($OldAuth, $PHP_AUTH_USER))) {
   authenticate();
  } 
  else {
   echo "<p>Welcome: $PHP_AUTH_USER<br>";
   echo "Old: $OldAuth";
   echo "<form action='$PHP_SELF' METHOD='POST'>\n";
   echo "<input type='hidden' name='SeenBefore' value='1'>\n";
   echo "<input type='hidden' name='OldAuth' value='$PHP_AUTH_USER'>\n";
   echo "<input type='submit' value='Re Authenticate'>\n";
   echo "</form></p>\n";
  }
?>

This behavior is not required by the HTTP Basic authentication standard, so you should never depend on this. Testing with Lynx has shown that Lynx does not clear the authentication credentials with a 401 server response, so pressing back and then forward again will open the resource as long as the credential requirements haven't changed. The user can press the '_' key to clear their authentication information, however.

Also note that this does not work using Microsoft's IIS server and the CGI version of PHP due to a limitation of IIS.

Note: If safe mode is enabled the uid of the script is added to the realm part of the WWW-Authenticate header.

User Contributed Notes
HTTP authentication with PHP
add a note about notes

21-Jul-1999 09:02

A few notes on authentication in which it's possible I overlooked some
things.  Considering a prior post about using the same salt for all users
so you can match passwords; I think it would be better to not do so, as
you can figure out the salt from the password and match.  (Example, salt
in DES if I'm not mistaken is the first 2 characters)
  Something I've been trying to figure out is secure apache module PHP on
a multi-user server.  
  Delima (with postgres)- any user can write a PHP page to read another
users databases.  Set your database to connect using username and
password, and any user can read your username and password from wherever
you place them.  (use PHP function to read it and as it has to be readable
by your web process for you to read it, they can)  
  The closest I've come to a solution for this is to run php as a CGI
module with suexec or cgiwrap.  
  Hopefuly someone else has a better solution; otherwise, something to
think about before you think of your databases as being secure with php
interfacing to them.


18-Dec-1999 12:42

Someone gave me a simple solution to the 'logout' problem: add some sort of
timestamp to the basic realm you send in the WWW_Authenticate header. Mine
now is: $realm="RealmName (
".strftime("%c",time())." )";. (btw: the problem
was: 1) IE4 asks for the page one more time after a 401, defeating sending
a 401 once to force a user to log on again. and 2) IE4 remembers the
password, and puts it default in the logon window. Changing the realm
solves these problems, not the 'logon failed' message of NS though).


02-Jan-2000 04:08

As an alternative check out PHPLIB at:


And the PHP Builder beginning/tutorial article called, "Session
Management and Authentication with PHPLIB" at 


09-Feb-2000 05:59

I had the same problem as above (that is, with apache I can't get the auth
info). The solution I found goes like this:

$headers = getallheaders();
$auth=$headers[authorization];
if ($auth=='') { $auth=$headers[Authorization]; }

if($auth=='')
{
	Header("WWW-Authenticate: Basic
realm=\"$PROG_NAME\"");
	Header("HTTP/1.0 401 Unauthorized");
}

list($user, $pass) = explode(":", base64_decode(substr($auth,
6)));


19-May-2000 08:31

Here is a code for the public sites enabling both logout bottom and timeout
using php+mysql. Working for both browsers.
The part "required" for each user protected page:

<?
function auth () {
        Header("WWW-Authenticate: Basic realm=\"ArmFN public
site\"");
        Header("HTTP/1.0 401 Unauthorized");
        echo "You have to authentificate yourself first \n";
        exit;
}

mysql_connect("localhost","train","") or
die("Unable to connect to SQL server"); 
mysql_select_db( "train") or die( "Unable to select
database"); 

if(!isset($PHP_AUTH_USER)) {

$timeout =
mktime(date(G),date(i)+10,0,date("m"),date("d"),date("Y"));
mysql_query("update users set login='$timeout' where id='$user' and
pasw='$pass'") or die("k");

	auth();

			} else {

    $pass = $PHP_AUTH_PW;
    $user = $PHP_AUTH_USER;

$nowtime =
mktime(date(G),date(i),0,date("m"),date("d"),date("Y"));
$quer2 = mysql_query("select * from users where id='$user' and
pasw='$pass' and login > '$nowtime'") or die("kuk2");

    if (mysql_num_rows($quer2) == "0") {
$timeout =
mktime(date(G),date(i)+10,0,date("m"),date("d"),date("Y"));
mysql_query("update users set login='$timeout' where id='$user' and
pasw='$pass'") or die("k");

auth();
}
		}
?>

You can have a "logout" bottom with hidden
$go="logout" form element and then have somewhere this part:

if ($do == "logout") {
mysql_connect("localhost","train","") or
die("Unable to connect to SQL server"); 
mysql_select_db( "train") or die( "Unable to select
database"); 
mysql_query("update users set login=0 where id='$PHP_AUTH_USER' and
pasw='$PHP_AUTH_PW'") or die("k");
}


30-Aug-2000 09:04

Good day.I've solved a problem where IE4 asks for the age one more time
after a 401, defeating sending a 401 once to force a user to log on
again.

  function  authenticate()  {
    setcookie("noauth","");
    Header( "WWW-authenticate:  Basic
realm=\"test\"");
    Header( "HTTP/1.0  401  Unauthorized");
	echo "You must enter user name";
   exit ;
  }
  if  (   !isset($PHP_AUTH_USER) ||  ($logoff==1) &&
$noauth=="yes"  )   {
	authenticate();
  }  

And logoff link -
 
<a
href="samehtml.phtml?logoff=1">Logoff</a></td>

Dmitry Alyekhin


16-Oct-2000 09:01

The new Mozilla browser doesn't seem to like the switched authentication
lines. 

This doesn't work (I have build 2000101308):

Header( "WWW-authenticate: Basic realm=\"test\"");
Header( "HTTP/1.0 401 Unauthorized");

The first time you authenticate all seems ok, but the second time it
always returns unauthorized.

This works as it should:

Header( "HTTP/1.0 401 Unauthorized");
Header( "WWW-authenticate: Basic realm=\"test\"");


20-Nov-2000 07:46

If you were trying to read the contents of $PHP_AUTH_USER or $PHP_AUTH_PW
from inside a function, you would first have to globalize them:

function Authenticat () {
    global $PHP_AUTH_USER;
    global $PHP_AUTH_PW;

    ...
}

Otherwise, PHP assumes that those variables are local to the function
Authenticate () and initializes them with NULL values.


28-Nov-2000 11:00

When calling in a function and using the $PHP_AUTH_USER and $PHP_AUTH_PW
against mysql connect I found I needed to omit the isset call and just
do:
if(!$PHP_AUTH_USER or !$PHP_AUTH_PW). Otherwise the
mysql_connect('host',$PHP_AUTH_USER,$PHP_AUTH_PW) call returns a value.
Also, in the checking for mysql_connect return value, I need to include
the auth headers again to get things working as expected.


10-Mar-2001 08:19

I suggest to read RFC2617 (HTTP Authentication: Basic and Digest Access
Authentication) and related RFCs.


05-Apr-2001 05:19

Thanks to [email protected] for the rfc note needed to solve this
one. This looks like it flushed out the authentication headers on both
Netscape and IE:
Header("WWW-Authenticate: Basic realm=\"Whatever Realm\",
stale=FALSE");


17-May-2001 09:55

You may enjoy this tutorial :


12-Jun-2001 09:53

This is a good resource for setting up htaccess schemes:



The windows version of apache comes with htpasswd.exe in the apache\bin
directory.

The only thing that present problems is you have to change your .htaccess
file to point to the created password file (ie
C:\directory\passwords.file)....so if you transfer the file back to a *nix
server it wont find your file.

One (temporary) workaround is changing your local httpd.conf file to point
to a different access file:

AccessFileName htaccess.

You just have to make sure to syncronize your access files.

Im not sure if you can point your htaccess to two password files??
 AuthName "restricted stuff"
 AuthType Basic
 AuthUserFile /usr/local/etc/httpd/users
 AuthUserFile C:\directory\password.file
 require valid-user


12-Jul-2001 07:51

If register_globals is turned off PHP_AUTH_USER and PHP_AUTH_PW variables
will not be set, instead they are stored in $HTTP_SERVER_VARS array as
$HTTP_SERVER_VARS['PHP_AUTH_USER'] and HTTP_SERVER_VARS['PHP_AUTH_PW'].

roberi[at]gmx[dot]net
15-Dec-2001 03:45

in 4.1.0 the variables are:

$_SERVER["PHP_AUTH_USER"]  and 
$_SERVER["PHP_AUTH_PW"]


28-Jan-2002 12:49

Does anyone know how to do the opposite ie: passing a username and password
to the http server in order for it to authenticate a given protected
directory???


28-Jan-2002 05:25

Restrict access by username, password AND ip address:

<?
function authenticate() {
	header("WWW-Authenticate: Basic realm=\":-!\"");
	header("HTTP/1.0 401 Unauthorized");
	print("You must enter a valid login username and password 
		to access this resource.\n");
	exit;
	}
if(!isset($PHP_AUTH_USER)){ authenticate(); }
else {
	$c=mysql_pconnect("server.name","user","password");
	mysql_select_db("dbname",$c);
	$q=sprintf("SELECT username,password FROM authenticateTable
		WHERE username='%s' AND password=PASSWORD('%s') 
		AND ipaddress='%s'",
			$PHP_AUTH_USER,$PHP_AUTH_PW,$REMOTE_ADDR);
	$q=mysql_query($q);
	if(mysql_num_rows($q)==0){ authenticate(); } 
}
?>


29-Jan-2002 09:00

To get it to work with IIS try using this code before setting your
"$auth = 0" and the "if (isset($PHP_AUTH_USER) &&
isset($PHP_AUTH_PW))"

//////////////////////////////////////////

if ($PHP_AUTH_USER == "" && PHP_AUTH_PW == ""
&& ereg("^Basic ", $HTTP_AUTHORIZATION)) 
{ 
  list($PHP_AUTH_USER, $PHP_AUTH_PW) = 
    explode(":", base64_decode(substr($HTTP_AUTHORIZATION, 6)));

}

//////////////////////////////////////////

It worked for me on IIS 5 and PHP 4 in ISAPI


22-Feb-2002 06:09

I tried the method posted by
[email protected] for a logout feature, which seems to be a problem for
users of http authentication. Tigran's method is perfect, except that
after you log out, you can STILL access the pages by clicking on
"cancel" when prompted again by the Java window. 
This will trigger the 401 error. But it will also create an entry in the
history folder. 

You will notice the "forward" button on your browser becomes
clickable. You only have to click on the that "forward" button
to be able to access the protected pages. 

I have found a solution for this problem by using a little Javascript to
refresh to another page.

Please go to my website for details:


28-Feb-2002 11:49

I use apache's built in support for .htaccess, and the following function
to grab user details as required.

Function GetHttpAuth()
{
        $headers = getallheaders();
        $auth=explode(" ",$headers[Authorization]);
if ($auth=='') { $auth=explode(" " ,$headers[authorization]); }

        $authdec=base64_decode($auth[1]);
        $autharray=explode(":",$authdec);
        $authname=$autharray[0];
        $authpass=$autharray[1];
        return($autharray);
}


22-May-2002 10:34

NOTE: For users of 4.2.0 and later. For this to work, you must deal with
the issue of the external variables not being registered in the global
scope by default. The quickest fix is to add register_globals = on to your
php.ini.


24-May-2002 01:55

If you want to access $PHP_AUTH_USER or $PHP_AUTH_PW variables via the
$GLOBALS variable, here is the good path:

$GlOBALS[_SERVER][$PHP_AUTH_USER] and $GlOBALS[_SERVER][$PHP_AUTH_PW]

In the messages above [_SERVER] was unspecified.

This is useful when you want to unset those variables in a function; then your test for the HTTP login prompt would be:

if ((!isset($PHP_AUTH_USER)) || ($PHP_AUTH_USER=="") { header("WWW-Authenticate: Basic realm=\"Login process\""); header("HTTP/1.0 401 Unauthorized"); ... } else { if ( =>here test if log/pass are the good one<= ) { ... ok } else { $GLOBALS['_SERVER']['PHP_AUTH_USER'=""; ...error message, user could log again } }



24-May-2002 02:22

The definitive HTTP authorization code:

function login_error()
{
 echo "error - login process failed."
}

if (!isset($PHP_AUTH_USER))
{
 header("WWW-Authenticate: Basic realm=\"Mosaic Authorization
process\"");
 header("HTTP/1.0 401 Unauthorized");

 //Result if user hits cancel button
 login_error();
}
else
{

 //check the login and password
 if('=>test on login and password<=')
 {
  //User is logged
  ...
  ...
 }
 else
 {
  //This re-asks three times the login and password.
  header( "WWW-Authenticate: Basic realm=\"Test Authentication
System\"");
  header("HTTP/1.0 401 Unauthorized");

  //Result if user does not give good login and pass
  login_error();
 }
}


02-Jun-2002 05:29

Using the same salt for all things is a bad idea.

Use the first two letters of the username - this also makes moving to
other .htaccess based systems easier :)

05-Jun-2002 08:08
A more elegant way to force a new name/password, cf. example 17-2 (if you
don't mind passing the old user in the query string):

<?
if (isset($PHP_AUTH_USER))
{
	if (!isset($prev_user))
	{
		header("Location: );
		exit;
	}
	else
	{
		if ($PHP_AUTH_USER == $prev_user)
		{
			header('WWW-Authenticate: Basic realm="Secure"');
			header('HTTP/1.0 401 Unauthorized');
			exit;
		}
	}
}
else
{
	header('WWW-Authenticate: Basic realm="Secure"');
	header('HTTP/1.0 401 Unauthorized');
	exit;
}
?>

The final set of headers is necessary because some browsers seem to unset
$PHP_AUTH_USER when the location header is sent.


07-Jun-2002 06:13

Hi,
Sometimes IE even after closing page remembers $PHP_AUTH_USER and
$PHP_AUTH_PW . is there any way to clean this buffer ?
Thanks.


19-Jun-2002 09:05

Now with the new super globals, these variables are stored in the $_SERVER
super global. Just use $_SERVER["PHP_AUTH_USER"] and
$_SERVER["PHP_AUTH_PW"] for PHP 4.1.x and higher.

20-Jun-2002 03:30
Seems that REMOTE_USER is only set in .htaccess Authentification not in PHP
header Authentifications


22-Jun-2002 08:32

Does anyone know how to do the opposite ie: passing a username and password
to the http server in order for it to authenticate a given protected
directory???


22-Jun-2002 08:59

Does anyone know how to do the opposite ie: passing a username and password
to the http server in order for it to authenticate a given protected
directory???


23-Jun-2002 09:15

Put it directly into the URL ?



27-Jun-2002 06:03

Is it possible to change these variables manually?

$_SERVER["PHP_AUTH_USER"]
$_SERVER["PHP_AUTH_PW"]

that way, it would be easy to make a logout script.

add a note about notes
previousCreating and manipulating imagesCookiesnext
Last updated: Tue, 28 May 2002
show source | credits | stats | mirror sites:  
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Thu Jul 4 12:06:15 2002 CEST