Page 1 of 1

Clear $_SERVER['PHP_AUTH_USER']???

Posted: Thu Mar 04, 2010 1:30 pm
by alex.barylski
According to some messages I've read setting 401 in headers like so:

Code: Select all

 
    header('WWW-Authenticate: Basic realm="Cadorath RPI Management"');
    header('HTTP/1.0 401 Unauthorized');
 
Will tell browsers NOT to cache the credentials. Doesn't appear to work in IE7/8

Here is my code:

Code: Select all

 
  echo $_SERVER['PHP_AUTH_USER'];
  exit;
 
  if($id_user == 0){
 
    // NOTE: Clear the browser cache of credentials we use $_SESSION for security
    header('WWW-Authenticate: Basic realm="Aerospace Management"');
    header('HTTP/1.0 401 Unauthorized');
 
    if(!empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW'])){
 
        // NOTE: Authenticate user against database and redirect to refresh display and show management console
        if($_SERVER['PHP_AUTH_USER'] == 'AlexB' && $_SERVER['PHP_AUTH_PW'] == 'AlexB'){
 
            $_SESSION['id_user'] = 1;
 
            unset($_SERVER['PHP_AUTH_USER']);
            unset($_SERVER['PHP_AUTH_PW']);
 
        header('Location: '.SYSTEM_SETTING_BASE);
        exit;
      }
    }
 
    echo 'Authentication failed. Please refresh your browser and try again.';
    exit;
    }
 
 
When my logout function executes and stomps on sessions because the browser automatically caches credentials it logs the user back in obviously not the desired funcitonality.

I do not want to use a standard HTML form I would like to know what is wrong with this code even before I move to something more standrad.

Cheers,
Alex

Re: Clear $_SERVER['PHP_AUTH_USER']???

Posted: Thu Mar 04, 2010 5:29 pm
by requinix
PCSpectra wrote:Will tell browsers NOT to cache the credentials.
Not quite.

Most browsers will cache credentials. That's a good thing. You can clear the "cache" - prompt for credentials again - by sending the 401 response again.

When you send a Location: PHP automatically sends a 302 or 307 response (I forget which). That will overwrite the 401 you gave before. The combination of a not-401 and a WWW-Authenticate probably confuses IE, to which it responds by redirecting without clearing the authentication details.

Try the Location first, the WWW-Authenticate second, and the 401 Unauthorized last. However the standard doesn't say anything about putting a Location: in a 401 so no guarantees.