我什么时候应该在没有 die() 的情况下调用 header('Location')


When should I call header('Location') without die()?

在它之后不die()的情况下调用header('Location:')有意义吗?

如果不是,为什么PHP解释器不自动执行die()?如果是,什么时候?

header('Location: ')将进行HTTP重定向,告诉浏览器转到新位置:

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>

为什么 die() 不是由 PHP 解释器自动执行的?

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()之后。

基本上,如果你不这样做,你的脚本可能会做不必要的额外计算,这些计算永远不会对用户"可见",因为服务器无论如何都会重定向他。

这个PHP用户说明中解释了一个很好的例子,复制在这里供后人参考:


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

这对于需要很长时间的任务很有用,例如转换视频或缩放大图像。