您的位置 首页 php

PHP中output buffering的原理及应用

php缓存过程

在请求一个PHP的过程中,实际上经过三个缓存:

1.程序缓存

2.ob缓存

3.浏览器缓存.

开启ob的两个方法

1.在php.ini 配置 ;output_buffering = 4096 这里去掉;号即可

2 在php页面中使用 ob_start();

通过php.ini 打开的,则作用于所有的php页面 。使用ob_start()打开则只作用于该页面

ob缓存的知识点

在服务中,如果我们开启了ob缓存,则echo数据首先放入到ob中

当PHP页面执行到最后,则会把ob缓存的数据(如果有的话), 强制刷新到程序缓存,然后通过apache对数据封装成http响应包,返 回给浏览器

如果没有ob,所有的数据直接放入程序缓存。 header信息不管你是否开启ob,总是放入到程序缓存。

ob相关的函数

ob_start($callback)

//在当前页面中开启ob,注意callbackob_start($callback);

ob_get_contents()

//获取当前ob缓存中的内容ob_get_contents()

ob_get_clean()

//获取当前ob缓存中的内容,并且清空当前的ob缓存ob_get_clean()

ob_flush()

//将ob缓存中的内容,刷到程序缓存中,但并没有关闭ob缓存ob_flush()

ob_end_flush()

//关闭ob缓存,并将数据刷回到程序缓存中ob_end_flush()

ob_clean()

//将ob缓存中的内容清空ob_clean()

ob_end_clean()

//将ob缓存中的数据清空,并且关闭ob缓存ob_end_clean()

注意ob_start($callback)的回调

<?phpob_start("callback_func");function callback_func($str){    return "callback".$str;}echo "123";//输出:callback123

应用场景

在header()发送之前的报错

出错代码

<?phpecho "before_header";header("Content-type:text/html;charset=utf-8");echo "after_header";

输出:

Warning: Cannot modify header information - headers already sent by (output started at /Users/shuchao/Desktop/test.php:2) in /Users/shuchao/Desktop/test.php on line 3

解决办法

在发送header前开启ob,则所有的echo内容都会到ob里面,从而解决错误。

<?phpob_start();echo "before_header\n";header("Content-type:text/html;charset=utf-8");echo "after_header\n";

输出

before_headerafter_header

以上就是PHP中output buffering的原理及应用的详细内容,更多请关注求知技术网其它相关文章!

文章来源:智云一二三科技

文章标题:PHP中output buffering的原理及应用

文章地址:https://www.zhihuclub.com/2949.shtml

关于作者: 智云科技

热门文章

网站地图