header()函数按照手册中的写法无法正常工作,出错可能在哪里?

4
我在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")可以设置头信息:

<!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>

怎么会这样?设置有问题吗?

1
可能是http输出后的重定向的重复问题。 - mario
3个回答

3

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,但是想通过代码演示前提条件)
注意:在脚本文件中,如果ini启用了output_buffering,则不需要使用ob_start,但是此处的目的是通过代码演示前提条件。

我已经检查了php.ini中的output_buffering。该值为4096。这是否意味着它是“开启”的?如何关闭它?谢谢。 - Green
1
@Green:是的,使用 On 或一个数字(表示以字节为单位的缓冲区大小)都可以打开它。禁用它非常简单,只需要将值赋为 Off 即可,例如 output_buffering=Off - Brad Christie

1

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接