the header 'WWW-Authenticate'

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I had a question about the use of the HTTP header 'WWW-Authenticate'
in PHP scripts. For example, the script below sends the header 'WWW-
Authenticate: Basic Realm="Secret Stash"', followed by the header
'HTTP/1.0 401 unauthorized', to force the web browser to display a
username/password dialog.  The script then calls exit().

I don't understand how the script gets re-invoked (after the username
and password have been supplied in the dialog box and user has clicked
because the script called exit() after issuing the two header() calls.

I understand that once the username and password have been supplied
that  $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] set.
But how does the server know to re-invoke the same script a second
time? After all the script just did an exit() after sending the

   // Preset authentication status to false.
   $authorized = FALSE;

   if (isset($_SERVER['PHP_AUTH_USER']) &&
isset($_SERVER['PHP_AUTH_PW'])) {

   // Read the authentication file into an array
   $authFile = file("./authenticationFile.txt");

        // Cycle through each line in file, searching for
authentication match.
    foreach ($authFile as $login) {

        list($username, $password) = explode(":", $login);

        // Remove the newline from the password
        $password = trim($password);

        if ($username == $_SERVER['PHP_AUTH_USER'] &&
        $password == md5($_SERVER['PHP_AUTH_PW'])) {

        $authorized = TRUE;

   // If not authorized, display authentication prompt or 401 error
   if (! $authorized) {

      header('WWW-Authenticate: Basic Realm="Secret Stash"');
      header('HTTP/1.0 401 Unauthorized');
      print('You must provide the proper credentials! Buster!!!');
// restricted material goes here...

Re: the header 'WWW-Authenticate' wrote:
Quoted text here. Click to load it

<snipped example>

Your script first checks if a username and a password are given and
exits only if that is not the case, sending a request header for

The client asks for the page (without the password and username being
sent), gets the request header and then displays a login dialog.
When the user has filled in the username and password, the page is
requested again, but now with credentials. So the browser just requests
the same page again with different headers.

Best regards,
Willem Bogaerts

Application smith
Kratz B.V. /

Re: the header 'WWW-Authenticate'

Quoted text here. Click to load it

Thanks Willem for the reply. While I did understand the logic of the
script, I wasn't familiar with was the fact that the http server
remembers the script that issued the
header('WWW-Authenticate: Basic Realm="Secret Stash"');
header('HTTP/1.0 401 Unauthorized');
and re-invokes. So it is the http server that "remembers" and then re-
invokes the same script that issued the 'wwww-Authenticate'.

Site Timeline