-5

In book of Welling and Thomson write follow code

if (($_SERVER['PHP_AUTH_USER'] != 'user') ||
($_SERVER['PHP_AUTH_PW'] != 'pass')) {
// visitor has not yet given details, or their
// name and password combination are not correct
header('WWW-Authenticate: Basic realm="Realm-Name"');
header('HTTP/1.0 401 Unauthorized');
echo "<h1>Go Away!</h1>
<p>You are not authorized to view this resource.</p>";
} else {
// visitor has provided correct details
echo "<h1>Here it is!</h1>
<p>I bet you are glad you can see this secret page.</p>";
}

What does header('HTTP/1.0 401 Unauthorized') do? I remove this line and script worked properly.

Why this code worked without this line?

Daniyal
  • 119
  • 3
  • 8
  • It's supposed to set a status code. Using a `HTTP/1.0` head is incorrect for most setups. It should be `Status:` normally. -- Your assessment that everything "worked properly" after removing it seems unlikely however. – mario Feb 15 '15 at 17:53
  • This code appears to function properly on my server.... what do you consider *not* working properly? – CragMonkey Feb 15 '15 at 18:06
  • @Cragmonkey I want to know why this code worked without this line? Thanks for your attention. – Daniyal Feb 15 '15 at 19:38

3 Answers3

1

The HTTP 401 header tells your browser that you are not authorized to view that page, which would be the expected situation if you attempted to access a protected resource by were not logged in.

Note: ALWAYS include die(); or exit; after sending a header like that, as bots don't necessarily obey the header instructions and you want to terminate the script before they see the protected content. This goes for redirects especially.

CragMonkey
  • 808
  • 1
  • 11
  • 22
0

The HTTP header that is being sent by that command is HTTP/1.0 401 Unauthorized which tells the browser that it needs to ask for a username or password to view the page.

Debug Diva
  • 26,058
  • 13
  • 70
  • 123
0

header("HTTP/1.0 401 Unauthorized"); sends the 401 status code of unauthorized to the server saying that you are not permitted to view the page. Use die or exit instead of echo to stop other code from being executed.

Joshua
  • 426
  • 1
  • 10
  • 18