理解PHP的标题()

时间:2009-08-09 02:12:53

标签: php header

您在哪里使用命令标题()?

我在handlers / handle_login.php上有以下代码。用户已从index.php转到该网站,这是起始位置。

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

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

3 个答案:

答案 0 :(得分:8)

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

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

http://www.yoursite.com/forms/contact/

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

header("Location: index.php");

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

http://www.yoursite.com/forms/contact/index.php

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

希望这有帮助。

答案 1 :(得分:4)

将位置设置为index.php的完整URL,而不仅仅是文件名。根据php.net,这是正确的方法,不要使用相对路径。这是一个例子:

 if(!$logged_in){
     header("Location: http://exampledomain.com/index.php");
     die("You are not logged_in");
 }

答案 2 :(得分:1)

尝试使用'/':

if(!$logged_in){
     header("Location: /index.php");                                                                          
     die("You are not logged_in");
 }

如果没有斜杠,则假定您指的是当前目录中的某些内容。通过在前面粘贴斜杠,您明确指的是站点根目录下的文件。由于页面是'index.php',你可以轻松使用“header('Location:/')”。