理解PHP的标题()

Léo*_* 준영 4 php header

你在哪里使用命令头()?

我在handlers/handle_login.php上有以下代码.用户已经到达index.php起始位置的站点.

 if(!$logged_in){
     header("Location: index.php");                                                                          
     die("You are not logged_in");
 }
Run Code Online (Sandbox Code Playgroud)

如果if-clause为true,我会收到404错误,因为标题会将我转到handlers/index.php,而不是index.php.

小智 8

虽然我同意nilamo和伯爵,但我希望我能给出更大的图景:

使用相对路径可能会产生非常奇怪的效果,具体取决于浏览器"认为"它在您的站点层次结构中的位置.例如,假设站点具有索引文件'/index.php',但配置为接受URI路径中的模块和操作.你可能有一个看起来像这样的网址:

http://www.yoursite.com/forms/contact/
Run Code Online (Sandbox Code Playgroud)

从这种情况看,返回如下标题:

header("Location: index.php");
Run Code Online (Sandbox Code Playgroud)

可能会导致浏览器尝试请求

http://www.yoursite.com/forms/contact/index.php
Run Code Online (Sandbox Code Playgroud)

这显然不是你想要的.出于这个原因,通常最好使用上面建议的'/index.php',或者甚至更好地使用完全限定的URL.

希望这可以帮助.

  • 我只想补充一点,HTTP/1.1 RFC明确指出标题Location中给出的URL必须是绝对的,而不是相对的:"字段值由单个绝对URI组成"(参见http://www.w3.org) /Protocols/rfc2616/rfc2616-sec14.html#sec14.30); 即使浏览器通常会聚合使用相对URL,也应该使用绝对URL (8认同)