search
HomeBackend DevelopmentPHP TutorialIntroduction to php ob cache and detailed explanation of ob function

ob cache introduction

ob is the abbreviation of output buffering, output buffer, and the buffer is controlled through the output_buffering variable in php.ini. Its default value is off and can be set to on to open the buffer. After calling the buffer, even if the ob function is not used in the program, the code actually uses the buffer. In addition, regardless of the setting of output_buffering in php.ini, php in cli mode is always turned off by default. Why a buffer? To put it simply, the high-speed CPU has processed its own data early and wants to transmit it to the user through the line, but the line is too narrow and cannot be transmitted at once. If a buffer is introduced, the CPU can quickly put the generated data into the buffer, and then rest somewhere cool. The buffer outputs data in a timely manner according to instructions. This effectively solves the contradiction between high-speed CPU and low-speed I/O devices.

Basic principles of ob: If the ob cache is turned on, the echo data is first placed in the 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.

The basic function of ob:

1) Prevent the use of setcookie(), header() or session_start() to send header files after the browser has output Error caused by function. 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 between Simplified and Traditional Chinese, and 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.

Detailed explanation of ob related functions

1. Flush: refresh the contents of the buffer and output.
Function format:

flush()

Description: This function is frequently used and is very efficient.
2. ob_start: Open the output buffer
Function format:

void ob_start(void)

Description: When the buffer is activated, all non-file header information from the PHP program will not be sent, but will be saved in Internal buffer. In order to output the contents of the buffer, you can use ob_end_flush() or flush() to output the contents of the buffer.
3, ob_get_contents: Return the contents of the internal buffer.
Usage:

string ob_get_contents(void)

Description: This function will return the contents of the current buffer. If the output buffer is not activated, it will return FALSE.
4. ob_get_length: Returns the length of the internal buffer.
Usage:

int ob_get_length(void)

Description: This function will return the length in the current buffer; the same as ob_get_contents, if the output buffer is not activated. then returns FALSE.
5. ob_end_flush: Send the contents of the internal buffer to the browser and close the output buffer.
Usage:

void ob_end_flush(void)

Description: This function sends the contents of the output buffer (if any).
6. ob_end_clean: Delete the contents of the internal buffer and close the internal buffer
Usage:

void ob_end_clean(void)

Description: This function will not output the contents of the internal buffer but delete it!
7. ob_implicit_flush: Turn on or turn off absolute flush
Usage:

void ob_implicit_flush ([int flag])

Description: Anyone who has used Perl knows the meaning of $|=x. This string can open/close the buffer. , and the ob_implicit_flush function is the same as that one. The default is to close the buffer. After turning on absolute output, each script output is sent directly to the browser, and there is no need to call flush()

The example code of the flush function is as follows:

<?php
for($i = 1; $i <= 300; $i++ ) print(" ");
// 这一句话非常关键,cache的结构使得它的内容只有达到一定的大小才能从浏览器里输出换言之,如果cache的内容不达到一定的大小,它是不会在程序执行完毕前输出的。经
// 过测试,发现这个大小的底限是256个字符长。这意味着cache以后接收的内容都会源源不断的被发送出去。
For($j = 1; $j <= 20; $j++) {
echo $j."";
flush(); //这一部会使cache新增的内容被挤出去,显示到浏览器上
sleep(1); //让程序"睡"一秒钟,会让你把效果看得更清楚
}
?>

Description: flush() is a very efficient function. Its very useful function is to refresh the cache# of browser ##.

About the example code of the ob series function:

For example, you can use the setting information of the server and the client, but this information will be different depending on the client. , what if you want to save the output of the phpinfo() function? Before there was no buffer control, it can be said that there was no way at all, but with buffer control, we can easily solve it.

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

Using the above method, you can save the phpinfo information of different users. This may not have been possible before! In fact, the above is a method to convert some "processes" into "functions"!

About the static template output example code:

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

The so-called static template technology is to use a certain method to make the user get the html page generated by PHP on the client side. . If this html page will no longer be updated, then when another user browses this page again, the program will no longer call PHP and related databases. For some websites with a large amount of information, technology like this will bring The benefits are huge.

【Related tutorial recommendations】

1. "

php.cn Dugu Jiujian (4)-php video tutorial"

2. A complete set of tutorials on PHP programming from entry to master

The above is the detailed content of Introduction to php ob cache and detailed explanation of ob function. 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
What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

How do you redirect a page in PHP?How do you redirect a page in PHP?Apr 28, 2025 pm 04:54 PM

The article discusses various methods for page redirection in PHP, focusing on the header() function and addressing common issues like "headers already sent" errors.

What is PDO in PHP?What is PDO in PHP?Apr 28, 2025 pm 04:51 PM

The article discusses PHP Data Objects (PDO), an extension for database access in PHP. It highlights PDO's role in enhancing security through prepared statements and its benefits over MySQLi, including database abstraction and better error handling.

What is Memcache and Memcached in PHP? Is it possible to share a single instance of a Memcache between several projects of PHP?What is Memcache and Memcached in PHP? Is it possible to share a single instance of a Memcache between several projects of PHP?Apr 28, 2025 pm 04:47 PM

Memcache and Memcached are PHP caching systems that speed up web apps by reducing database load. A single instance can be shared among projects with careful key management.

What are the steps to create a new database using MySQL and PHP?What are the steps to create a new database using MySQL and PHP?Apr 28, 2025 pm 04:44 PM

Article discusses steps to create and manage MySQL databases using PHP, focusing on connection, creation, common errors, and security measures.

Does JavaScript interact with PHP?Does JavaScript interact with PHP?Apr 28, 2025 pm 04:43 PM

The article discusses how JavaScript and PHP interact indirectly through HTTP requests due to their different environments. It covers methods for sending data from JavaScript to PHP and highlights security considerations like data validation and prot

See all articles

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor