Home Backend Development PHP Tutorial PHP deeply understands the usage of refresh buffer function

PHP deeply understands the usage of refresh buffer function

May 24, 2018 pm 04:26 PM
php function refresh go deep understand buffer

About how to use ob_flush() and flush() in PHP

Note: The two functions ob_flush() and flush() are generally used together, and the order is First ob_flush(), then flush(), their function is to refresh the buffer.
Here is a detailed explanation of when to use the refresh buffer and why to refresh the buffer.

1. When to refresh the buffer

When the two functions file_get_contents() and file_put_contens() are used in the program, Or when performing similar "read and write" functions in the program or performing output operations to the browser, ob_flush() and flush() will be used to refresh the buffer.

2. Why the buffer should be refreshed

Use file_get_contents() and file_put_content() as examples to explain.

The two functions file_get_contents() and file_put_conents() respectively perform reading data and writing data operations. The data is first read into the memory and then written to the file, because the reading speed is faster than The writing speed should be fast, so when your data is read, it does not mean that the data has been written. At this time, the more read content will be temporarily placed in the buffer (memory). It needs to be emphasized here, In fact, data reading and writing are two very fast actions.

Also use an explanation (when the program performs an output operation to the browser), individual web server programs, especially web server programs under Win32, will still cache the script before sending the results to the browser. Output until the end of the program. If you don't want the program to be output to the browser only after it is executed, then you can also use ob_flush() and flush() to refresh the cache.

In fact, flush() has another use, which is to output before the program ends. That is, part of the results can be output to the browser before a loop ends. This effect is very similar to the asynchronous ajax. transmission effect.
In-depth understanding of the difference between ob_flush and flush
The description of ob_flush/flush in the manual is to refresh the output buffer, and it also needs to be used in conjunction, so it will cause many people to be confused...
Actually, they operate on different objects. In some cases, flush does nothing at all..
ob_* series of functions operate the output buffer of PHP itself.
So, ob_flush refreshes PHP itself. Buffer.
And flush, strictly speaking, this only has practical effect when PHP is installed as apache Module (handler or filter). It refreshes the buffer of WebServer (can be considered specifically apache) .
Under the sapi of apache module, flush will indirectly call the apache api by calling the flush member function pointer of sapi_module: ap_rflush refreshes the output buffer of apache. Of course, the manual also says, There are some other modules of Apache, which may change the result of this action..Some Apache modules, such as mod_gzip, may perform output caching by themselves, which will cause the results generated by the flush() function to not be sent to the client immediately. end browser.
Even the browser will cache the received content before displaying it. For example, the Netscape browser caches content until it receives a newline or the beginning of an html tag, and does not display an entire table until it receives a tag.
Some versions of Microsoft Internet Explorer will only start displaying the page after receiving 256 bytes, so some extra spaces must be sent to allow these browsers to display the page content. Therefore, the correct order to use the two is. First ob_flush, then flush,
Of course, under other sapi, you can not call flush, but to ensure the portability of your code, it is recommended to use it together.

buffer --- - flush()

Buffer is a memory address space. The default size of the Linux system is generally 4096 (1kb), which is one memory page. It is mainly used to store data transfer areas between devices with unsynchronized speeds or devices with different priorities. Through the buffer, the processes can wait less for each other. Here is a more general example. When you open a text editor to edit a file, every time you enter a character, the operating system will not immediately write the character directly to the disk, but first write it to the buffer. When writing When a buffer is full, the data in the buffer will be written to the disk. Of course, when the kernel function flush() is called, it is mandatory to write the dirty data in the buffer back to the disk.
Similarly, when echo and print are executed, the output is not immediately transmitted to the client browser for display through tcp, but the data is written to the php buffer. The php output_buffering mechanism means that a new queue is established before the tcp buffer, and data must pass through the queue. When a php buffer is full, the script process will hand over the output data in the php buffer to the system kernel and pass it to the browser via TCP for display. Therefore, the data will be written to these places in sequence echo/pring -> php buffer -> tcp buffer -> browser
php output_buffering --- ob_flush()
Default Next, the php buffer is enabled, and the default value of the buffer is 4096, which is 1kb. You can find the output_buffering configuration in php.iniConfiguration File. When echo, print, etc. output user data, the output data will be written to php output_buffering. Until output_buffering is full, the data will be Transmitted to the browser for display via tcp. You can also manually activate the php output_buffering mechanism through ob_start(), so that even if the output exceeds 1kb of data, the data will not be actually handed over to tcp and passed to the browser. Because ob_start() will The buffer space is set to be large enough. The data will not be sent to the client browser until the end of the script or the ob_end_flush function is called.

The use of these two functions is probably the most confusing issue for many people. The explanation of the two functions in the manual is not clear, and their differences are not clearly pointed out. It seems that the functions of both are the same. is to flush the output cache. But in the code at the beginning of our article, if flush() is replaced with ob_flush(), the program will no longer execute correctly. Obviously, there is a difference between them. Otherwise, it would be enough to directly state in the manual that one of them is an alias of another function. There is no need to explain them separately. So what is the difference between them?
When caching is not enabled, the content output by the script is in a state of waiting for output on the server side. flush() can immediately send the content waiting for output to the client.

After the cache is turned on, The content output by the script is stored in the output cache. At this time, there is no content waiting for output. If you use flush() directly, it will not send any message to the client. content. The function of ob_flush() is to take out the content that originally existed in the output cache, and set it to the waiting output state, but it will not be sent directly to the client . In this case, you need to use ob_flush() first and then Using flush(), the client can immediately get the output of the script.

1. The correct order of flush and ob_flush, the correct order should be, ob_flush first and then flush, as follows:
ob_flush();
flush();
If the Web server If the operating system is Windows, then there will be no problem if the order is reversed or if ob_flush() is not used. [To be verified ] However, the output buffer cannot be refreshed on Linux systems.
output buffering function
1.bool ob_start ([ callback $output_callback [, int $chunk_size [, bool $erase ]]] )
Activate the output_buffering mechanism . Once activated, the script output is no longer sent directly to the browser, but is temporarily written to the PHP buffer memory area.
php enables the output_buffering mechanism by default, but by calling the ob_start() function, the data output_buffering value is expanded to a large enough value. You can also specify $chunk_size to specify the value of output_buffering. The default value of $chunk_size is 0, which means that the data in the php buffer will not be sent to the browser until the end of the script. If you set the size of $chunk_size, it means that as long as the data length in the buffer reaches this value, the data in the buffer will be sent to the browser.
Of course, you can process the data in the buffer by specifying $ouput_callback. For example, the function ob_gzhandler compresses the data in the buffer and then sends it to the browser.
The third parameter: whether to erase the cache, optional, the default is true, if set to false, the cache will not be cleared before the script execution ends.
2.ob_get_contents
Get a copy of the data in the php buffer. It is worth noting that you should call this function before the ob_end_clean() function is called, otherwise ob_get_contents() returns a null character.
You can use ob_get_contents() to obtain the server-side cached data in the form of a string.
Using ob_end_flush() will output the cached data and close the cache.
Using ob_end_clean() will silently clear the data cached on the server without any data or other actions.
The caches on the server are stacked, which means that after you enable ob_start() and before closing it, you can open another cache ob_start() inside it.
But you must also ensure that the number of operations to turn off the cache is the same as the number of operations to turn on the cache.
ob_start() can specify a callback function to process cache data . If one ob_start() is nested inside another ob_start(), we assume that the outer The ob_start() number of the layer is A, and the ob_start() number of the inner layer is B. They each have a callback function called functionA and functionB. Then when the data in cache B is output, it will be processed by the funcitonB callback function. , and then handed over to the outer functionA callback function for processing, and then can be output to the client.
In addition, the manual says that for some web servers, such as apache, using the callback function may change the current working directory of the program. The solution is to manually modify the working directory back in the callback function, using the chdir function. This does not seem to be encountered often, so remember to check the manual when you encounter it.
3.ob_end_flush and ob_end_clean
These two functions are somewhat similar and both turn off the ouptu_buffering mechanism. But the difference is that ob_end_flush only flushes (flush/send) the data in the php buffer to the client browser, while ob_clean_clean clears (erase) the data in the php bufeer but does not send it to the client browser.
Before ob_end_flush is called, the data in the php buffer still exists, and ob_get_contents() can still obtain a copy of the data in the php buffer.

After calling ob_end_flush(), ob_get_contents() gets an empty string, and the browser cannot receive output, that is, there is no output.

You can use ob_get_contents() to obtain the server-side cached data in the form of a string, and use ob_end_flush() to output the cached data and close the cache.
Using ob_end_clean() will silently clear the data cached on the server without any data or other actions.

The above is the detailed content of PHP deeply understands the usage of refresh buffer function. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles