douyue7536 2012-11-08 06:52
浏览 58
已采纳

PHP HTTP身份验证,如果条件语句

<?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?

  • 写回答

1条回答 默认 最新

  • doujiao7679 2012-11-08 07:19
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)
  • ¥66 比特币地址如何生成taproot地址