<?php
if (!isset($_SERVER['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';
exit;
} else {
echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>
This piece of code kind of defies the logic behind the way an "if" control structure works. But I have seen the same thing in many pieces of code so for some reason it must be right. Yet my logic tells me otherwise.
Of course the condition of "!isset($_SERVER['PHP_AUTH_USER']))
checks to see if this variable is set on the server. Let's say that it is not set. So the server sends a request to the client requiring HTTP Authentication "header('WWW-Authenticate: Basic realm="My Realm"');"
and let's say that I provide one that is correct. After this, somehow the "if"
control structure skips the " header('HTTP/1.0 401 Unauthorized');"
and the echo statement and the rest of the control structure. Why is this?
The script runs twice.
First it goes into the first block, sends the headers and the "Text to send if user hits Cancel button" text to the browser, and then stops (see the exit
). The PHP script is terminated completely and forgets that anything has ever happened.
The control is handed to the browser, where you enter a password. (At this point, the browser already has received the cancel button text, but is prevented from showing it due to the 401 status header.) After you enter the password, the control goes back to the server and the script is executed again from the top, and now (having the password sent) it runs into the second part.
If you press escape instead, the browser removes the password dialog and simply displays what it already received during the first execution (the cancel button text).
You can follow this by looking into the access log of your webserver.