【发布时间】:2012-05-30 23:12:07
【问题描述】:
在没有die() 的情况下调用header('Location:') 是否有意义?
如果不是,为什么 PHP 解释器不自动执行 die()?如果有,什么时候?
【问题讨论】:
标签: php redirect http-headers location die
在没有die() 的情况下调用header('Location:') 是否有意义?
如果不是,为什么 PHP 解释器不自动执行 die()?如果有,什么时候?
【问题讨论】:
标签: php redirect http-headers location die
header('Location: ') 将使HTTP redirect 告诉浏览器转到新位置:
HTTP/1.1 301 Moved Permanently
Location: http://example.com/another_page.php
Connection: close
它不需要任何 HTML 正文,因为浏览器不会显示它,只需遵循重定向即可。这就是为什么我们在header('Location:') 之后调用die() 或exit()。如果您不终止脚本,HTTP 响应将如下所示。
HTTP/1.1 301 Moved Permanently
Location: http://example.com/another_page.php
Connection: close
<!doctype html>
<html>
<head>
<title>This is a useless page, won't displayed by the browser</title>
</head>
<body>
<!-- Why do I have to make SQL queries and other stuff
if the browser will discard this? -->
</body>
</html>
为什么 PHP 解释器不自动执行 die()?
header()函数用于发送原始HTTP头,不限于header('Location:')。例如:
header('Content-Type: image/png');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// ...more code...
在这种情况下,我们不会调用die(),因为我们需要生成 HTTP 响应正文。所以如果PHP在header()之后自动调用die()是没有意义的。
【讨论】:
在我个人看来,当您不想再执行该脚本时,您应该致电die()。如果您不希望脚本在您的 header("Location: ...") 之后执行,您应该在其后面加上 die()。
基本上,如果您不这样做,您的脚本可能会进行不必要的额外计算,因为服务器无论如何都会重定向用户,因此这些计算永远不会对用户“可见”。
【讨论】:
header("Location:...") 之后不需要做任何事情,则无需担心,只需将die 放在其后即可。
this PHP user note 中解释了一个很好的例子,复制到这里供后人使用:
arr1 建议继续的简单但有用的包装 告诉浏览器输出完成后处理。
当请求需要一些处理时,我总是重定向(所以我们不会 刷新时执行两次)这让事情变得简单......
<?php
function redirect_and_continue($sURL)
{
header( "Location: ".$sURL ) ;
ob_end_clean(); //arr1s code
header("Connection: close");
ignore_user_abort();
ob_start();
header("Content-Length: 0");
ob_end_flush();
flush(); // end arr1s code
session_write_close(); // as pointed out by Anonymous
}
?>
这对于需要很长时间的任务很有用,例如转换视频或缩放大图像。
【讨论】:
die() 在Location 之后是有意义的!另外,我相信session_write_close() 应该出现在Location 标题之前,而不是最后。