Home >Backend Development >PHP Tutorial >Detailed explanation of ob series function output cache usage

Detailed explanation of ob series function output cache usage

伊谢尔伦
伊谢尔伦Original
2017-06-24 11:49:251518browse

ob, output buffer, is the abbreviation of output buffering, not output cache. If ob is used correctly, it will help the speed to a certain extent, but adding the ob function blindly will only increase the extra burden on the CPU.

The basic principle of ob: If the ob cache is turned on, the echo data will be sent first Put it in ob cache. If it is header information, it is placed directly in the program cache. When the page is executed to the end, the ob cached data will be placed in the program cache, and then returned to the browser in turn.
Let’s talk about the basic functions of ob:
1) Prevent the use of functions such as setcookie(), header() or session_start() to send header files after the browser has output. mistake. In fact, it is better to use this kind of usage less often and develop good coding habits.
2) Capture the output of some unobtainable functions. For example, phpinfo() will output a lot of HTML, but we cannot use a variable such as $info=phpinfo(); to capture it. At this time, ob will be useful. .
3) Process the output content, such as gzip compression, conversion from Simplified to Traditional Chinese, or some string replacement.
4) Generating static files is actually capturing the output of the entire page and then saving it as a file. Often used in HTML generation or full page caching.

Regarding the GZIP compression mentioned in the third point just mentioned, many people may want to use it, but have not actually used it. In fact, by slightly modifying the code, you can achieve gzip compression of the page.

ob_start(ob_gzhandler);
要缓存的内容

Yes, just add a callback function ob_gzhandler, but there are some minor problems with this. First, it requires zlib support, and second, it does not determine whether the browser supports gzip (it seems to support it now) , iPhone browsers seem to support it).
The previous approach was to determine whether the browser supports gzip, then use the third-party gzip function to compress the content of ob_get_contents(), and finally echo.

1. Collection of commonly used functions in the ob series functions

##ob_start(); to the browser, but saved in the output buffer.

ob_clean();                 //Delete the contents of the internal buffer without closing the buffer (no output).

ob_end_clean(); //Delete the contents of the internal buffer and close the buffer (no output).
ob_get_clean(); //Return the contents of the internal buffer and close the buffer. Equivalent to executing ob_get_contents() and ob_end_clean()
ob_flush();                                                                                  ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​sends the content of the buffer, deletes the content of the buffer, does not close the buffer.
ob_end_flush(); //Send the contents of the internal buffer to the browser, delete the contents of the buffer, and close the buffer.
ob_get_flush(); //Return the contents of the internal buffer, close the buffer, and then release the contents of the buffer. Equivalent to ob_end_flush() and returns the buffer contents.
flush();                                                // Output the content released by ob_flush and the content not in the PHP buffer to the browser; refresh the content of the internal buffer and output it.

ob_get_contents(); //Return the contents of the buffer without output.


ob_get_length(); //Returns the length of the internal buffer. If the buffer is not activated, this function returns FALSE. ob_get_level(); //Return the nesting level of the output buffering mechanism.
ob_get_status(); //Get status of output buffers.

ob_implicit_flush(); //Turn on or off absolute refresh. The default is off. After turning on ob_implicit_flush(true), the so-called absolute refresh means that when an output statement (e.g: echo) is executed, the output is sent directly to the browser and is no longer needed. Call flush() or wait until the end of the script to output.

ob_gzhandler //ob_start callback function, uses gzip to compress the contents of the buffer.


ob_list_handlers //List all output handlers in use
output_add_rewrite_var //Add URL rewriter values
output_reset_rewrite_vars //Reset URL rewriter values

这些函数的行为受php_ini设置的影响:
output_buffering       //该值为ON时,将在所有脚本中使用输出控制;若该值为一个数字,则代表缓冲区的最大字节限制,当缓存内容达到该上限时将会自动向浏览器输出当前的缓冲区里的内容。
output_handler         //该选项可将脚本所有的输出,重定向到一个函数。例如,将 output_handler 设置为 mb_output_handler() 时,字符的编码将被修改为指定的编码。设置的任何处理函数,将自动的处理输出缓冲。
implicit_flush         //作用同ob_implicit_flush,默认为Off。

二、实例讲解

1、使 header() 函数前可以有echo代码
Output Control 函数可以让你自由控制脚本中数据的输出。它非常地有用,特别是对于:当你想在数据已经输出后,再输出文件头的情况。
输出控制函数不对使用 header() 或 setcookie(),发送的文件头信息产生影响,只对那些类似于 echo() 和 PHP 代码的数据块有作用。  

ob_start();                   //打开缓冲区  
echo "Hello\n";               //输出  
header(“location:index.php”); //把浏览器重定向到index.php   
ob_end_flush();               //输出全部内容到浏览器

所有对header()函数有了解的人都知道,这个函数会发送一段文件头给浏览器,但是如果在使用这个函数之前已经有了任何输出(包括空输出,比如空格,回车和换行)就会提示出错。如果我们去掉第一行的ob_start(),再执行此程序,我们会发现得到了一条错误提示:"Header had all ready send by"!但是加上ob_start,就不会提示出错,原因是当打开了缓冲区,echo后面的字符不会输出到浏览器,而是保留在服务器,直到你使用flush或者ob_end_flush才会输出,所以并不会有任何文件头输出的错误!
2、保存 phpinfo() 函数的输出

ob_start();                      //打开缓冲区   
phpinfo();                       //使用phpinfo函数   
$info = ob_get_contents();       //得到缓冲区的内容并且赋值给$info   
$file = fopen('info.txt', 'w');  //打开文件info.txt   
fwrite($file, $info);            //写入信息到info.txt   
fclose($file);                   //关闭文件info.txt

3、静态模版技术
所谓静态模版技术就是通过某种方式,使得用户在client端得到的是由PHP产生的html页面。如果这个html页面不会再被更新,那么当另外的用户再次浏览此页面时,程序将不会再调用PHP以及相关的数据库,对于某些信息量比较大的网站,例如sina、163、sohu。类似这种的技术带来的好处是非常巨大的。 

ob_start();                            //打开缓冲区
php页面的全部输出   
$content = ob_get_contents();          //取得php页面输出的全部内容   
$fp = fopen("output00001.html", "w");  //创建一个文件,并打开,准备写入   
fwrite($fp, $content);                 //把php页面的内容全部写入output00001.html,然后……   
fclose($fp);

三、输出缓存句柄ob_gzhandler
PHP4.0.4有一个新的输出缓存句柄ob_gzhandler,它与前面的类相似,但用法不同。使用ob_gzhandler时要在php.ini中加入的内容如下:  

output_handler = ob_gzhandler;

这行代码使得PHP激活输出缓存,并压缩它发送出去的所有内容。

如果由于某种原因你不想在php.ini中加上这行代码,你还可以通过PHP源文件所在目录的.htaccess文件改变默认的服务器行为(不压缩),语法如下:    

php_value output_handler ob_gzhandler

或者是从PHP代码调用,如下所示:

ob_start("ob_gzhandler");

采用输出缓存句柄的方法确实非常有效,而且不会给服务器带来什么特殊的负荷。但必须注意的是,Netscape Communicator对压缩图形的支持不佳,因此除非你能够保证所有用户都使用IE浏览器,否则你应该禁止压缩JPEG和GIF图形。一般地,对于所有其他文件,这种压缩都有效,但建议你针对各种浏览器都分别进行测试,特别是当你使用了特殊的插件或者数据查看器时这一点尤其重要。
注意事项:
1、一些Web服务器的output_buffering默认是4069字符或者更大,即输出内容必须达到4069字符服务器才会flush刷新输出缓冲,为了确保flush有效,最好在ob_flush()函数前有以下语句:

print str_repeat("", 4096);  //以确保到达output_buffering值

2、ob_* 系列函数是操作PHP本身的输出缓冲区,所以ob_flush只刷新PHP自身的缓冲区,而flush是刷新apache的缓冲区。所以,正确使用俩者的顺序是:先ob_flush,然后flush。ob_flush是把数据从PHP的缓冲中释放出来,flush是把缓冲内/外的数据全部发送到浏览器。
3、不要误认为用了ob_start()后,脚本的echo/print等输出就永远不会显示在浏览器上了。因为PHP脚本运行结束后,会自动刷新缓冲区并输出内容。

The above is the detailed content of Detailed explanation of ob series function output cache usage. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn