最近一直在学习PHP,看了一篇关于PHP缓存技术原理的文章——《用PHP的ob_start()控制您的浏览器cache、生成html》,按照例子写代码,如下代码:
<?php
ob_start(); //打开缓冲区
echo "Hello\n"; //输出
header("location:index.php"); //把浏览器重定向到index.php
ob_end_flush(); //输出全部内容到浏览器
?>
小盘在本机做了一下测试,发现在无论调不调用ob_end_flush都能输出 Hello 并且提示“Header had all ready send by”错误!感觉ob_start()无效没起作用。于是百度之,谷歌之不得其解。自己感觉问题应该在配置文件中没有打开缓存功能,于是打开php.ini文件,CTRL+F查找 ob_start ,找到一段注释:
; You can redirect all of the output of your scripts to a function. For
; example, if you set output_handler to "mb_output_handler", character
; encoding will be transparently converted to the specified encoding.
; Setting any output handler automatically turns on output buffering.
; Note: People who wrote portable scripts should not depend on this ini
; directive. Instead, explicitly set the output handler using ob_start().
; Using this ini directive may cause problems unless you know what script
; is doing.
问题解决方法:
没有管什么意思,查看前后文,找到一句output_buffering = Off 顿时明白,问题果然是将缓存关闭了,将Off改为On,如果前面有; 将分号去掉,重启Apache,这样不调用ob_end_flush就能输出的问题就解决了!