php - 我应该在调用 Location: header 后调用 exit() 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3553698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php - Should I call exit() after calling Location: header?
提问by q0987
After calling the redirect function header, should I call exit or not?
调用重定向函数头后,是否应该调用exit?
<?php // fileA
$urlFailToGoTo = '/formerror.php';
if (sth)
{
header(sprintf("Location: %s", $urlFailToGoTo));
exit(); //should I call exit() here? or return?
}
?>
Thank you
谢谢
回答by rgroli
You definitely should. Otherwise the script execution is not terminated. Setting another header alone is not enough to redirect.
你绝对应该。否则脚本执行不会终止。单独设置另一个标头不足以重定向。
回答by Jan Turoň
You should, just like @rgroli explains. If you do not want to bother with brackets, you can also call header()
INexit()
:
你应该,就像@rgroli 解释的那样。如果你不想打扰括号,你也可以调用header()
INexit()
:
if(sth) exit(header("Location: http://example.com"));
Location header in HTTP/1.1 always requires absolute path see the note here.
HTTP/1.1 中的位置标头总是需要绝对路径,请参阅此处的注释。
Note:This is not a hack, since the exit codeis used only if the parameter is integer, while header()
produces void (it exits with code=0, normal exit). Look at it as exit_header()
function like it should be after Location
header.
注意:这不是 hack,因为退出代码仅在参数为整数时使用,而header()
产生 void(它以代码 = 0 退出,正常退出)。将它视为exit_header()
函数,就像它应该在Location
标题之后一样。
回答by Amber
It's generally good practice to exit;
(note - it's a keyword, so you don't need the ()
) after sending a Location:
header, since browsers are supposed to redirect to the new page and so further execution of the current script is usually undesired.
在发送标头之后exit;
(注意 - 它是一个关键字,因此您不需要()
)通常是一种很好的做法Location:
,因为浏览器应该重定向到新页面,因此通常不希望进一步执行当前脚本。
回答by Hydrino
If you don't have any code (PHP or HTML) under header, you don't have to.
如果标题下没有任何代码(PHP 或 HTML),则不必这样做。
回答by Benjamin Eckstein
exit is bad coding.
退出是糟糕的编码。
if you ever develop a big project and want to create PHP Unit Testcases, exit will screw you up.
如果你曾经开发过一个大项目并且想要创建 PHP 单元测试用例,exit 会让你大吃一惊。
exit terminates the script and your running test! there is no way to recover the test and tell if it has failed or not ...
exit 终止脚本和您正在运行的测试!没有办法恢复测试并判断它是否失败了......
organise your code the way, that there is no output and the script ends naturally if you use a redirect ...
以这种方式组织您的代码,如果您使用重定向,则没有输出并且脚本自然结束......