The 5th Annual China PHP Conference


Please answer this simple SPAM challenge: six minus three?
(Example: nine)

The Note You're Voting On

10 years ago
I couldn't get authentication to work properly with any of the examples. Finally, I started from ZEND's tutorial example at: (validate using .htpasswd) and tried to deal with the additional cases. My general conclusion is that changing the realm is the only reliable way to cause the browser to ask again, and I like to thank the person who put that example in the manual, as it got me on the right path. No matter what, the browser refuses to discard the values that it already has in mind otherwise. The problem with changing the realm, of course, is that you don't want to do it within a given session, else it causes a new request for a password. So, here goes, hopefully the spacing isn't too messed up by the cut'n'paste.

I spent the better part of a day getting this to work right. I had a very hard time thinking through what the browser does when it encounters an authentication request: seems to me that it tries to get the password, then reloads the page... so the HTML doesn't get run. At least, this was the case with IE, I haven't tested it with anything else.

() ;
if (!isset(
$_SESSION['realm'])) {
$_SESSION['realm'] = mt_rand( 1, 1000000000 ).
" SECOND level: Enter your !!!COMPANY!!! password.";

header( "WWW-Authenticate: Basic realm=".$_SESSION['realm'] );

//  Below here runs HTML-wise only if there isn't a $_SESSION,
        // and the browser *can't* set $PHP_AUTH_USER... normally
        // the browser, having gotten the auth info, runs the page
        // again without getting here.
        //  What I'm basically getting to is that the way to get
        // here is to escape past the login screen. I tried
        // putting a session_destroy() here originally, but the
        // problem is that the PHP runs regardless, so the
        // REFRESH seems like the best way to deal with it.
echo "<meta http-equiv=\"REFRESH\"

if (
$_POST['logout'] == "logout") {
session_destroy() ;
header('Location: comeagain.php');
        exit ;

// "standard" authentication code here, from the ZEND tutorial above.

comeagain.php is as follows:

"<html><head><title>Logged Out</title><h1>Logout Page</h1><body>" ;
"You have successfully logged out of TOGEN";
" at ".date("h:m:s")." on ".date("d F Y") ;
"<p><a href=\"index.php\">Login Again</a>" ;
"</body></html>" ;

The idea is to be able to trash the session (and thus reset the realm) without prompting the browser to ask again... because it has been redirected to logout.php.

With this combination, I get things to work. Just make sure not to have apache run htpasswd authentication at the same time, then things get really weird :-).

<< Back to user notes page

To Top