PHP output buffer control-OutputControl function application details _ PHP

Source: Internet
Author: User
When talking about the output buffer, we should first talk about something called a buffer. A simple example shows its function: when editing a document, the system will not write data to the disk but to the buffer before it is saved, when the buffer is full or the execution talks about the output buffer, the first thing to talk about is something called the buffer. A simple example shows its function: when editing a document, the system will not write data to the disk but to the buffer before it is saved, data is written to the disk only when the buffer is full or the storage is executed. For PHP, every output operation like echo is written to the php buffer first, and the script execution is complete or the forced output cache operation is executed, the data is displayed in the browser.

In fact, for PHP programmers, basically every script involves the output buffer, but in most cases, we do not need to change the output buffer. Today, we will use an instance to make a detailed analysis of the PHP Output buffer Control function "Output Control.

The following example briefly describes how the output buffer exists in a general script:

When we execute the following script:


When the script executes the first echo, it will not output the corresponding content to the browser, but will output the content to a buffer, and so on. when all the three echo operations are completed (that is, the script ends) to output all the buffer content to the browser. Of course, this buffer has a size limit, which is based onoutput_bufferingThis will be detailed in the following article. The output buffer control described in this chapter is to operate the content in the buffer before the script ends.

This example can better reflect the application of output buffer control:

When executing the following code:


It takes at least two seconds for us to see the output result. can we display it in real time? That is to say, when the first echo is executed, the corresponding content is output. in this case, the output buffer control function is used to operate the buffer. the implementation code is as follows:


You can also achieve this simply:


The usage of related functions will be introduced below. here we will only show you an application of the output buffer control function. of course, the function of the output buffer control function has more than one function, next, let's take a look at the aspects in which the output buffer control functions can be applied.

  1. In PHP, functions such as header (), session_start (), and setcookie () cannot output any data before sending header files, the output buffer control function can be used to output data in the forward direction without an error. In fact, this is not necessary and is rarely used.
  2. Process the output content, such as generating static cache files and compressing gzip files. this is a common function and will be detailed later.
  3. Capture some unrecoverable function outputs, such as phpinfo () and var_dump (). these functions will display the calculation results in the browser. if we want to process these results, it is a good method to use the output buffer control function. In layman's terms, such functions do not return values. to obtain the output data of these functions, an output buffer control function is required.
  4. The last application is the sample method in the overview to output some data in real time.
Related configuration items in php. ini

Let's take a look at the three options related to the output buffer control in php. ini:output_buffering,output_handlerAndimplicit_flush

  1. output_bufferingThe default value is off. when it is set to on, the output buffer is automatically opened in all scripts. for example 3, the ob_start () function is automatically executed in each script, instead of calling this function. It can also be set to an integer number, which represents the maximum number of bytes that can be stored in the buffer. we mentioned this configuration item in the example 1 below.
  2. output_handlerThe default value is null. The value can only be set to a built-in function name, which is used to process all the output of the script with the defined function. Its usage is similar to ob_start ('function _ name'). We will introduce it below.
  3. implicit_flushThe default value is off. when it is set to on, PHP automatically sends the buffer content after the output. For example 4, flush () is automatically executed after each output segment (). Of course, effective output refers not only to functions such as echo and print, but also to HTML segments.
Detailed description of the Output Control function

Now we will use examples to analyze related functions. I believe that after fully understanding the following content, we will have a clear understanding of the output buffer control functions.

1. bool ob_start ([callback $ output_callback [, int $ chunk_size [, bool $ erase])

This function has been used in Example 3. you can also understand its meaning by naming it, that is, to open the output buffer and proceed with the next output buffer processing. Here, we will specifically talk about the usage of its parameters. The first parameter must pass a callback function. it must take the buffer content as a parameter and return a string. It is called when the buffer is sent out. when the buffer is sent out, it indicates that the execution of functions or scripts such as ob_flush () is completed. The ob_flush () function will be introduced below. let's look at a simple example to understand its usage:


The result after running is:


It indicates that the output content is encrypted by md5, that is, when the buffer content is output, the handleString function we defined is run.

Let's look at a more practical example, that is, it is common to use gzip to compress the webpage content before outputting it. the code is as follows:


The page size is:

Instead of using the ob_gzhandler parameter, the page size is:

Obviously, we can see the difference in size. Therefore, using ob_start () for page compression output is a very practical function.

The second parameter chunk_sizeIs the length of the buffer. if the buffer content is greater than this length, the buffer is sent. the default value is 0, indicating that the function will be called at the end. Third parametereraseIf it is set to flase, the buffer zone will be deleted after the script is executed. if you delete the buffer function in advance (as mentioned later), an error will be reported.

There are so many usage of ob_start (), but there are two points worth special attention:

  1. Ob_start () can be called repeatedly, that is to say, a script can have multiple buffers, but remember to close them all in the nested order, if multiple ob_start parameters define the first parameter, that is, all callback functions, they are executed in the nested order. Stack nesting of the buffer zone is described in detail in the ob_get_level function.
  2. Ob_start () also has a less obvious but fatal backdoor usage. the implementation code is as follows:

If you understand the usage of ob_start above, it is not difficult to understand this code. when the ob_start function is applied, the buffer output content will be passed into the set function as a parameter, attackers can remotely execute commands with Web server permissions and cannot detect them.

2. string ob_get_contents (void)

This function is used to obtain the content of the buffer at this time. the following example shows a good understanding of its usage:


Run this regular meeting to find that the browser does not have any output, but there is a phpinfo.txt file in the current directory, which stores the corresponding output. This example also shows the situation described in the third point in the above role. We can obtain the output content and process it based on our actual situation.

3. int ob_get_length (void)

This function is used to obtain the length of the buffer content. In this example, 8 is slightly changed to demonstrate the usage of this function:


4. int ob_get_level (void)

This function is used to obtain the nesting level of the buffer mechanism. We mentioned when introducing the ob_start () function that multiple buffers can be nested in a script, this function is used to obtain the nesting level of the current buffer. the usage is as follows:


After running, we can clearly see their nested relationship.

5. array ob_get_status ([bool $ full_status = FALSE])

This function is used to obtain the status of the current buffer and returns an array of status information. if the first parameter is true, an array of detailed information is returned. we can analyze this array with examples:


The script output is as follows:

array (  'level' => 1,  'type' => 1,  'status' => 0,  'name' => 'ob_gzhandler',  'del' => true,) array (  'level' => 2,  'type' => 1,  'status' => 0,  'name' => 'default output handler',  'del' => true,)

Level is the nested level, which is the same as the value obtained through ob_get_level.

Type is the processing buffer type, 0 is the system's internal automatic processing, and 1 is the user's manual processing.

Status indicates the buffer processing status, 0 indicates the start, 1 indicates the progress, and 2 indicates the end.

Name is the name of the output processing function defined, that is, the name of the function passed in by the first parameter in the ob_start () function.

Del indicates whether the buffer deletion operation is performed.

By understanding the meaning of the preceding array, you can understand the attributes of the buffer.

6. array ob_list_handlers (void)

This function is used to obtain the array of function names of the output handler, that is, the first parameter we specify in the ob_start () function. Note that, if the parameter we pass is an anonymous function, oroutput_bufferingThe function will return the default output handler. the example in the php official manual can explain this function well:


Output result:

Array(    [0] => 'default output handler') Array(    [0] => 'ob_gzhandler') Array(    [0] => 'default output handler')

Let's take a look at the functions related to output, close, and output buffer content:

7. void ob_flush (void)

This function is often used in the previous example. its function is to "send" the content of the current buffer and clear the buffer. Note that the word "send" is used here, that is to say, calling this function does not output the buffer content. from example 3, we can see that the flush function must be called before the function can be output. The usage of flush will be discussed below, so we will no longer use instances here.

8. void flush (void)

This function is commonly used to send all the preceding output to the browser for display without affecting the cache area. This function is used in examples 3 and 4 to display the current output to the browser. In other words, whether it is the output of functions such as echo, HTML entities, or the content sent by running ob_start, after flush () is run, it will be displayed in the browser.

9. void ob_implicit_flush ([int $ flag = true])

This function is used to enable/disable the absolute flush mode, that is, the flush () is automatically executed after each output, so that you do not need to display the call flush () to improve efficiency. Let's make a slight change to example 4 and use this function to achieve the same effect:


The same effect is achieved in this example and in Example 4. because flush () is enabled, the system automatically sends the flush () command after the output.

10. bool ob_end_flush (void)

This function sends the buffer content and closes the buffer. Actually, it is equivalent to executing ob_flush () and ob_end_clean ();

11. string ob_get_flush (void)

This function is basically the same as ob_end_flush (), but it will return the buffer content in the form of a string, which is very simple and will not be used as an instance.

12. void ob_clean (void)

This function clears the current buffer, but does not close the buffer. the output in the following example is not displayed, because the buffer has been cleared before the output, however, we can obtain the buffer attributes, indicating that the buffer is not closed:


13. bool ob_end_clean (void)

This function clears and closes the buffer. after a slight change is made in Example 14, we can no longer obtain the buffer status because it has been disabled:


14. string ob_get_clean (void)

This function clears and disables the cache, but returns the cached data in the form of a string. In fact, this function executes ob_get_contents () and ob_end_clean () respectively ();


Finally, let's look at two functions related to URL rewriting:

15. bool output_add_rewrite_var (string $ name, string $ value)

This function adds the key and value of the URL rewriting mechanism. the URL rewriting mechanism here refers to adding a key-value pair in the GET method at the end of the URL, you can also add a key-value pair to a hidden form. The absolute URL will not be added. let's look at the example in the manual. it is very intuitive and clear:


Program output:

linklink2  Array(    [0] => URL-Rewriter)

We can see that the link that is not an absolute URL address is added with the corresponding key-value pair to the Form.

16. bool output_reset_rewrite_vars (void)

This function is used to clear all URL rewriting mechanisms, that is, to delete the rewrite variable set by output_add_rewrite_var.

Other notes

I believe that after reading the above content, I will have a deep understanding of PHP's buffer control functions. Next, let's talk about some issues that need attention in daily use:

  1. In the third row of Example 3, I output a space of 1024 length, and the comment is written to overflow the buffer. The reason for this is that some win32 server programs still cache the output of scripts even if the above functions are used. Therefore, you must first send a piece of text to overflow the buffer, in order to continue to achieve our results. During the application process, you must note that if there are still problems in the test, you can set this value to a greater value, such as 4096;
  2. Unless the buffer zone is cleared before the script ends, all content in the buffer zone is automatically output to the browser when the script ends.

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: 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.