【问题标题】:header() function doesn't work as written in the manual. Where the error can be?header() 函数不像手册中所写的那样工作。错误可能在哪里?
【发布时间】:2012-06-24 23:40:59
【问题描述】:

header() 函数有一些问题。它可以工作,也不能同时工作。

手册说:

请记住,必须在任何实际输出之前调用 header() 通过普通 HTML 标记、文件中的空行或 PHP 发送。

否则会报错。

但我可以在发送输出后在 html 脚本或 php 代码中的任何位置调用 header() 并且 header() 有效:

<?php
   echo "Output here";
   header("Location: http://stackoverflow.com");    // it works, it redirects to the site
   echo "And output here";
?>

任何header() 都有效。这个header("Some-Header: bar-foo")可以设置header:

<!DOCTYPE html>
<html>
   <body>

     … some script here…

    <?php
      print_r(headers_list());      // only one header: [0] => X-Powered-By: PHP/5.3.5
      header("Some-Header: bar-foo")
      print_r(headers_list());      // two headers: [0] => X-Powered-By: PHP/5.3.5
                                                    [2] => Some-Header: bar-foo
      var_dump(headers_sent($file, $line)); // bool(false)
      var_dump($file); // string(0) ""
      var_dump($line); // int(0)
    ?>

     … some script here…

   </body>
</html>

怎么可能?设置有问题吗?

【问题讨论】:

标签: php http-headers httpresponse response.redirect


【解决方案1】:

如果输出缓冲打开并且您写入标头,则可能会发生这种情况 在第一次冲洗之前。见http://www.php.net/manual/en/ref.outcontrol.php#ini.output-buffering

【讨论】:

    【解决方案2】:

    php.ini 可能启用了output_buffering,这是规则的例外。例如

    <?php
    
      ob_start();
      echo 'Foo';
      header('Location: http://www.google.com/');
      echo 'Bar';
      ob_end_flush();
    

    (注意:如果ini启用了output_buffering,则脚本文件中不需要ob_start,但想通过代码演示前提)

    【讨论】:

    • 我检查了 php.ini 中的output_buffering。值是4096,是不是就是on?如何关闭它?谢谢
    • @Green:是的,On 或数字(以字节为单位表示缓冲区大小)表示它已打开。禁用它就像分配值Off 一样简单。例如output_buffering=Off
    【解决方案3】:

    我认为你的 php 配置文件有问题,可能在你的 php.ini 中,你将 output_buffering 设置为非关闭值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-16
      • 1970-01-01
      • 2020-04-23
      • 2022-01-25
      • 1970-01-01
      相关资源
      最近更新 更多