Jquery中文网 www.jquerycn.cn
Jquery中文网 >  脚本编程  >  php  >  正文 PHP中output buffering的原理及应用

PHP中output buffering的原理及应用

发布时间:2020-10-28   编辑:www.jquerycn.cn
jquery中文网为您提供PHP中output buffering的原理及应用等资源,欢迎您收藏本站,我们将为您提供最新的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,注意callback ob_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)的回调

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

应用场景

在header()发送之前的报错

出错代码

<?php echo "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里面,从而解决错误。

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

输出

before_header after_header

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

  • 本文转载于:segmentfault,如有侵犯,请联系jquerycn@qq.com删除
  • 您可能感兴趣的文章:
    关于输出缓冲的讨论(Output buffering)之一
    图解PHP文件下载原理实例
    PHP中output buffering的原理及应用
    php header & http
    php 杜绝Cannot add header information
    php输出缓冲的小例子
    php输出缓存ob系列函数用法
    php中ob_get_contents();ob_end_clean();ob_start();用法详解
    PHP压缩CSS文件示例代码
    php 创建缩略图实例教程

    [关闭]