为什么此标题位置重定向在内容已回显后起作用?
<?
echo "lalala";
header("Location: http://www.google.com/");
如果我将其放入一个普通的 php 文件中,并使用 mod-php(PHP 版本 5.3.2-1ubuntu4.10)通过标准 apache2 服务器进行交付,则重定向到 google 的工作正常。
<?
echo "lalala";
flush();
header("Location: http://www.google.com/");
这段代码显然不会产生有效的重定向。
我的问题是第一个代码是如何处理的以及为什么它有效。因为我记得有些时候这样的事情是不可能的。 mod-php 或 apache 是否足够智能来缓冲整个请求并将标头排列在内容之前?
并且:
如果我确保不手动刷新输出,我可以依赖这个吗?因为这会让我的申请变得更加容易......
<?
echo "lalala";
header("Location: http://www.google.com/");
If i put this in a plain php file and deliver over a standard apache2 server with mod-php (PHP Version 5.3.2-1ubuntu4.10) the redirect to google works.
<?
echo "lalala";
flush();
header("Location: http://www.google.com/");
this code does obviously not produce a working redirect.
My question is how the first code is beeing processed and why it works. Because I remember times when things like this were not possible. Is mod-php or apache intelligent enough to buffer the whole request and arrange headers before content?
And:
Can I rely on this if I make sure I don't flush the output manually? Because it would make my application much easier...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
输出缓冲可能默认启用。如果您想依赖此功能,您应该手动启用它。
http://php.net/manual/en/function.ob-start.php
Output buffering is probably enabled by default. You should enable it manually if you want to rely on this functionality.
http://php.net/manual/en/function.ob-start.php
header 函数将一个 http 公共标头添加到 HTTP 响应中。因此,重定向已设置,浏览器会在显示输出之前收到 302 消息。
lush 命令 php 发送在调用它时已经准备好的 http 响应。这就是为什么第二个代码不会设置标头(必须在发送任何输出之前设置标头)。
并且,PHP 不应该输出任何内容,直到:
最后,在输出控制上检查此 http://www.php.net/manual/en/intro.outcontrol.php
The header function ADDS an http common header to the HTTP response. So, the redirect is setted and the browser gets the 302 message before showing you the output.
flush orders php to send the http response already prepared at the point it is called. That's why the second code won't set the header (it must be setted before sending ANY output).
And, the PHP should not output a single thing until:
Finally, check this on output control http://www.php.net/manual/en/intro.outcontrol.php