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

Detailed explanation of ob series function output cache usage

Jun 24, 2017 am 11:49 AM
function usage series cache output

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);
要缓存的内容
Copy after login

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();               //输出全部内容到浏览器
Copy after login

所有对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
Copy after login

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);
Copy after login

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

output_handler = ob_gzhandler;
Copy after login

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

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

php_value output_handler ob_gzhandler
Copy after login

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

ob_start("ob_gzhandler");
Copy after login

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

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

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Xiaomi 15 series full codenames revealed: Dada, Haotian, Xuanyuan Xiaomi 15 series full codenames revealed: Dada, Haotian, Xuanyuan Aug 22, 2024 pm 06:47 PM

The Xiaomi Mi 15 series is expected to be officially released in October, and its full series codenames have been exposed in the foreign media MiCode code base. Among them, the flagship Xiaomi Mi 15 Ultra is codenamed "Xuanyuan" (meaning "Xuanyuan"). This name comes from the Yellow Emperor in Chinese mythology, which symbolizes nobility. Xiaomi 15 is codenamed "Dada", while Xiaomi 15Pro is named "Haotian" (meaning "Haotian"). The internal code name of Xiaomi Mi 15S Pro is "dijun", which alludes to Emperor Jun, the creator god of "The Classic of Mountains and Seas". Xiaomi 15Ultra series covers

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

The best time to buy Huawei Mate 60 series, new AI elimination + image upgrade, and enjoy autumn promotions The best time to buy Huawei Mate 60 series, new AI elimination + image upgrade, and enjoy autumn promotions Aug 29, 2024 pm 03:33 PM

Since the Huawei Mate60 series went on sale last year, I personally have been using the Mate60Pro as my main phone. In nearly a year, Huawei Mate60Pro has undergone multiple OTA upgrades, and the overall experience has been significantly improved, giving people a feeling of being constantly new. For example, recently, the Huawei Mate60 series has once again received a major upgrade in imaging capabilities. The first is the new AI elimination function, which can intelligently eliminate passers-by and debris and automatically fill in the blank areas; secondly, the color accuracy and telephoto clarity of the main camera have been significantly upgraded. Considering that it is the back-to-school season, Huawei Mate60 series has also launched an autumn promotion: you can enjoy a discount of up to 800 yuan when purchasing the phone, and the starting price is as low as 4,999 yuan. Commonly used and often new products with great value

Caching mechanism and application practice in PHP development Caching mechanism and application practice in PHP development May 09, 2024 pm 01:30 PM

In PHP development, the caching mechanism improves performance by temporarily storing frequently accessed data in memory or disk, thereby reducing the number of database accesses. Cache types mainly include memory, file and database cache. Caching can be implemented in PHP using built-in functions or third-party libraries, such as cache_get() and Memcache. Common practical applications include caching database query results to optimize query performance and caching page output to speed up rendering. The caching mechanism effectively improves website response speed, enhances user experience and reduces server load.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

See all articles