Usage of php buffer output_buffering

Source: Internet
Author: User
This article provides a detailed analysis of php buffer output_buffering. For more information, see Buffer
Buffer is a memory address space. the default size of a Linux system is generally 4096 (4 KB), that is, a memory page. It is mainly used for data transmission between devices with different storage speeds or devices with different priorities. Through the buffer, the mutual waits of processes can be reduced. Here is a simple example. when you open a text editor and edit a file, the operating system does not immediately write this character to the disk for each input, instead, it is written to the buffer first. when the buffer is full, the data in the buffer is written to the disk. of course, when the kernel function flush () is called, the dirty data in the buffer must be written back to the disk.

In the same way, when echo and print are executed, the output is not immediately transmitted to the client browser through tcp, but 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 sends the output data in the php buffer to the system kernel and sends it to the browser for display. Therefore, the data will be written to the following places in sequence:Echo/print-> php buffer-> tcp buffer-> browser

Php output_buffering
By default, php buffer is enabled, and the default value of this buffer is 4096, that is, 4 KB. You can use. in the ini configuration file, find output_buffering configuration. when echo, print, and other user data are output, the output data will be written to php output_buffering until output_buffering is fully written. The data will be transmitted to the browser over tcp for display. You can also manually activate php output_buffering through ob_start (), so that even if the output exceeds 4 kB, the data is not really sent to the browser over tcp, because ob_start () set the php buffer space to large enough. Data is sent to the client browser only after the script is completed or the ob_end_flush function is called.

1. when output_buffering = 4096, and a small amount of data is output (less than one buffer)

The code is as follows:


For ($ I = 0; $ I <10; $ I ++ ){
Echo $ I .'
';
Sleep ($ I + 1 );//
}
?>


Symptom: no intermittent output occurs every few seconds, but the output can be viewed at a time until the response ends. the browser interface remains blank until the server script processing ends. This is because the data volume is too small, and php output_buffering is not full. Data writing order, which is echo-> php buffer-> tcp buffer-> browser

2. when output_buffering = 0, and a small amount of data is output (less than one buffer)

The code is as follows:


// Ini_set ('output _ buffering ', 0) does not take effect
// Edit/etc/php. ini and set output_buffering = 0 to disable the output buffering mechanism.
// Ini_set ('output _ buffering ', 0); // completely disable the output buffering function
For ($ I = 0; $ I <10; $ I ++ ){
Echo $ I .'
';
Flush (); // notifies the underlying operating system to send data to the client browser as soon as possible
Sleep ($ I + 1 );//
}
?>


Symptom: it is inconsistent with the display just now. after the php buffering mechanism is disabled, intermittent output can be seen intermittently in the browser, and the output does not have to be seen until the script is executed. This is because the data is not stuck in php output_buffering. The data write order is echo-> tcp buffer-> browser.

3. when output_buffering = 4096. the output data is greater than a buffer and ob_start () is not called ()

The code is as follows:


# // Create a 4 kB file
$ Dd if =/dev/zero of = f4096 bs = 4096 count = 1
For ($ I = 0; $ I <10; $ I ++ ){
Echo file_get_contents ('./f4096'). $ I .'
';
Sleep ($ I + 1 );
}
?>


Symptom: the response is not over yet (the http connection is not closed). intermittent output is displayed intermittently, and the browser interface is not left blank. Although the php output_buffering mechanism is enabled, the output will still be intermittent, rather than one-time, because the output_buffering space is insufficient. Every time a php buffering is filled, the data is sent to the client browser.

4. when output_buffering = 4096, the output data is greater than a tcp buffer and ob_start () is called ()

The code is as follows:


Ob_start (); // enable php buffer
For ($ I = 0; $ I <10; $ I ++ ){
Echo file_get_contents ('./f4096'). $ I .'
';
Sleep ($ I + 1 );
}
Ob_end_flush ();
?>


Symptom: The complete output is not displayed until the script processing on the server end and the response is complete. the output interval is very short, so that you cannot feel the pause. Before the output, the browser maintains a blank page, waiting for the server data. This is because, once php calls the ob_start () function, it will extend the php buffer to a large enough value, the data in the php buffer is sent to the client browser only after the ob_end_flush function call or the completion speed of script running.

Output buffering function

1.Ob_get_level
Return the nesting level of the output buffer mechanism,You can prevent the template from repeatedly embedding itself.

1. ob_start
Activate the output_buffering mechanism. Once activated, the script output is not directly sent to the browser, but is temporarily written to the php buffer memory area.

By default, php enables the output_buffering mechanism. However, by calling the ob_start () function, the value of output_buffering is extended to a large enough value. You can also specify $ chunk_size to specify the value of output_buffering. $ Chunk_size: The default value is 0, indicating that data in php buffer will not be sent to the browser until the script stops running. If you set the size of $ chunk_size, it indicates 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 specify $ ouput_callback to process data in the buffer. For example, the ob_gzhandler function compresses the data in the buffer and then transmits it to the browser.

2. ob_get_contents
Obtain a copy of data in the php buffer. It is worth noting that you should call this function before calling the ob_end_clean () function; otherwise, ob_get_contents () returns an empty character.

3. ob_end_flush and ob_end_clean
These two functions are similar, and the ouptu_buffering mechanism is disabled. But the difference is that ob_end_flush only flush the data in the php buffer to the client browser, while ob_clean_clean clears the data in the php bufeer (erase), but does not send it to the client browser. After ob_end_flush is called, data in php buffer still exists, and ob_get_contents () can still obtain data copies in php buffer. After ob_end_clean () is called, ob_get_contents () gets an empty string, and the browser cannot receive the output, that is, no output.

Typical cases
Ob_start () is often used in some template engines and page file caches. The following is the program code for loading the template in wet CI:

The code is as follows:


/*
* Buffer the output
*
* We buffer the output for two reasons:
* 1. Speed. You get a significant speed boost.
* 2. So that the final rendered template can be
* Post-processed by the output class. Why do we
* Need post processing? For one thing, in order
* Show the elapsed page load time. Unless we
* Can intercept the content right before it's sent
* The browser and then stop the timer it won't be accurate.
*/
Ob_start ();
// If the PHP installation does not support short tags we'll
// Do a little string replacement, changing the short tags
// To standard PHP echo statements.
If (bool) @ ini_get ('Short _ open_tag ') === false and config_item ('rewrite _ short_tags') = TRUE)
{
// Replace the short Mark
Echo eval ('?> '. Preg_replace ("/; * \ s * \?> /",";?> ", Str_replace (' }
Else
{
Include ($ _ ci_path); // include () vs include_once () allows for multiple views with the same name
}

// Record debugging information
Log_message ('debug', 'File loaded: '. $ _ ci_path );
// Return the file data if requested
If ($ _ ci_return = TRUE)
{
$ Buffer = ob_get_contents ();
@ Ob_end_clean ();
Return $ buffer;
}
/*
* Flush the buffer... or buff the flusher?
*
* In order to permit views to be nested
* Other views, we need to flush the content back out whenever
* We are beyond the first level of output buffering so that
* It can be seen and attached Ded properly by the first encoded ded
* Template and any subsequent ones. Oy!
*
*/
If (ob_get_level ()> $ this-> _ ci_ob_level + 1)
{
Ob_end_flush ();
}
Else
{
// Add the template content to the output stream
$ _ Ci_CI-> output-> append_output (ob_get_contents ());
// Clear the buffer
@ Ob_end_clean ();
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.