【问题标题】:PHP Header Redirect Working Despite Previous Earlier HTML and echo Output?尽管以前的 HTML 和 echo 输出较早,但 PHP 标头重定向仍然有效?
【发布时间】:2016-07-13 19:35:40
【问题描述】:

有人知道为什么这个脚本在我尝试过的每台服务器上都能成功吗?尽管在标头调用之前有较早的输出,但我已成功重定向到 Google。

根据PHP documentation,表示输出后添加headers失败并返回警告。但是,我在我的 Web 服务器上看到不一致的行为。我一直在使用类似的方法来完成一些事情,除了随机停止工作的一种情况外,它工作得很好。

<?php
    echo "lol"; 
?>
<html>
<?php
    header("Location: http://www.google.com");
    exit();
?>

那么,交易是什么?最新版本的 PHP 现在允许这样做吗?

我的 php 版本是 Ubuntu 14.04 x64 上的 PHP 5.5.9-1ubuntu4.14

【问题讨论】:

  • 很可能 PHP 做了一些缓存(输出缓冲区),这就是为什么有时它会起作用 ;)
  • 如果 PHP 在默认情况下推迟所有输出,这样您就可以在需要时注入标头,那将是很好的。不过我想知道真正的原因。
  • 如果您想“推迟”输出,可以使用以下功能:php.net/manual/en/book.outcontrol.php。另一方面,并​​发输出对于许多用例来说非常重要......
  • 谢谢,但这需要我做更多的工作:(。为什么 PHP 与它的文档不一致?上面的脚本工作的事实并不是很令人放心。
  • 这取决于您的服务器配置。如果您默认打开了输出缓冲,则您的代码不应返回错误。所以从这个意义上说,文档我没有错。见:php.net/manual/en/…

标签: php html redirect http-headers echo


【解决方案1】:

在我的服务器上启用了 Output_buffering,这允许其中的一些设置解释:

; Output buffering is a mechanism for controlling how much output data
; (excluding headers and cookies) PHP should keep internally before pushing that
; data to the client. If your application's output exceeds this setting, PHP
; will send that data in chunks of roughly the size you specify.
; Turning on this setting and managing its maximum buffer size can yield some
; interesting side-effects depending on your application and web server.
; You may be able to send headers and cookies after you've already sent output
; through print or echo. You also may see performance benefits if your server is
; emitting less packets due to buffered output versus PHP streaming the output
; as it gets it. On production servers, 4096 bytes is a good setting for performance
; reasons.
; Note: Output buffering can also be controlled via Output Buffering Control
;   functions.
; Possible Values:
;   On = Enabled and buffer is unlimited. (Use with caution)
;   Off = Disabled
;   Integer = Enables the buffer and sets its maximum size in bytes.
; Note: This directive is hardcoded to Off for the CLI SAPI
; Default Value: Off
; Development Value: 4096
; Production Value: 4096
; http://php.net/output-buffering
output_buffering = 4096

呃,php。

【讨论】:

  • 一个不错的副作用是,启用 output_buffering 会使脚本更快,至少在我的服务器上是 7.0.4,哈哈。
猜你喜欢
  • 2018-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-22
  • 1970-01-01
相关资源
最近更新 更多