PHP Output Buffer Control series function detailed

Source: Internet
Author: User
Tags bool flush ini php code sleep

This article mainly introduces the PHP output Buffer control series function detailed, this article explains the output buffer of the introduction, output buffering function, php.ini in the relevant configuration items, output control function, such as detailed content, need friends can refer to the

Overview

Previously studied PHP input and output buffer, but after the blog moved, the original article can not find, today saw a good article, by the way reproduced over.

Brief introduction

When it comes to output buffering, the first thing to say is something called a buffer (buffer). A simple example illustrates his role: when we edit a document, the system does not write to the disk until we save it, but writes it to the buffer and writes the data to disk when the buffer is full or the save operation is performed. For PHP, every output operation like Echo is written to the PHP buffer first, and the data is displayed on the browser after the script completes or the force output cache is executed.

In fact, for PHP programmers, almost every script involves an output buffer, but in most cases we don't need to change the output buffer. And today to use the example of the PHP output buffer control function "output controls" to do a detailed analysis.

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

The code is as follows:

Echo ' Apple ';

Echo ' IBM ';

Echo ' Microsoft '

When we execute the script above, the script does not output the content to the browser when it finishes its first echo, but it outputs it to a buffer, and so on, and so on, when all three Echo is finished (that is, the script ends), the contents of the buffer are all exported to the browser. Of course, this buffer is also limited in size, based on the output_buffering option in PHP.ini, which is described in detail in the following article. The output buffer control described in this chapter is the operation of the contents of the buffer before the end of the script.

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

The code is as follows:

Echo ' Apple '; Sleep (2);

Echo ' IBM '; Sleep (2);

Echo ' Microsoft ';

We need to wait at least 2 seconds to see the output, so can we let it show in real time? That is, at the end of the first echo to output the corresponding content, this time need to use output buffer control function to operate the buffer, the specific implementation of the first side, the article will be published at the conclusion.

Role

1. In PHP, such as header (), Session_Start (), Setcookie (), such as the function of sending header files, can not have any output, and the use of output buffer control functions can be output before these functions without error. In fact, there is no need to do so, very rare usage.

2. The output of the content processing, such as the generation of static cache files, gzip compression output, which is more commonly used functions.

3. Capturing some of the unreachable 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 such functions do not have a return value, and to obtain the output data of these functions, it is necessary to use the output buffer control function.

4. The final application is the real-time output of some of the data mentioned in the introduction.

Related configuration items in php.ini

Take another look at the php.ini and output buffer control related options, a total of three, respectively: Output_buffering, Implicit_flush and Output_handler.

1.output_buffering defaults to OFF, and when set to on, all scripts automatically open the output buffer, and the function is automatically executed in each script, Ob_start (), without having to be shown again. It can also be set to an integer number that represents the maximum number of bytes the buffer can store, as we mentioned in the description below in Example 1.

2.implicit_flush defaults to OFF, and when set to ON, PHP automatically sends out buffer content after the output. is to automatically execute flush () after each output. Of course, effective output refers not only to functions like Echo, print, but also to HTML segments.

3.output_handler default is NULL, and its value can only be set to a built-in function name, which is to handle all the output of the script with the defined function. His usage is similar to Ob_start (' function_name '), as described below.

In this article, if it is not specifically stated, the values of output_buffering, Implicit_flush, and Output_handler in php.ini are the default values.

Output Control function detailed

Ob_start ()

BOOL Ob_start ([Callback outputcallback[,intchunk_size [, BOOL $erase]])

This function can also be known from the name of its meaning, is to open the output buffer, so that the next step of the output buffer processing. This is specifically about the use of its arguments, the first parameter passing a callback function that takes the buffer contents as arguments and returns a string. He will call the buffer when it is sent out, which means executing functions such as ob_flush () or executing the script. The Ob_flush () function is described below to see a simple example to understand its usage:

The code is as follows:

function dothing1 ($echo _thing) {

Return ' # '. $echo _thing. '# ';

}

Ob_start (' dothing1 ');

Echo ' Apple ';

Output results

#Apple #

From the results of the output can be seen on both sides of the word has been added "#", that is, in the buffer content output, ran the DOTHING1 function we defined.

To see a more practical example, which is common to the content of the Web page to use gzip compression and then output, the code is as follows:

The code is as follows:

Ob_start ();

echo str_repeat (' Apple ', 1024);

Output: The output size is 5.2KB without gzip compression.

Output: With gzip compression, the document size is much smaller, the compression takes time, so the time is long.

The second parameter, Chunk_size, is the byte length of the buffer, and if the buffer content is greater than this length, the buffer will be sent out, the default value is 0, and the function will be invoked at the end. The third parameter erase if it is set to Flase, the buffer will 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 need special attention:

1.ob_start () can be called repeatedly, that is, there can be multiple buffers in a script, but remember to close them all in a nested order, and if multiple Ob_start define the first parameter, which means that all the callback functions are defined, they are executed sequentially in the nesting order. The stack nesting of buffers, described in detail in the Ob_get_level function, is not explained here.

2.ob_start () also has a less obvious but fatal backdoor usage that implements the following code:

The code is as follows:

$cmd = ' System ';

Ob_start ($cmd);

Echo $_get[' a '];

Ob_end_flush ();

The output below windows:

14 Directory 30,970,388,480 Free bytes

If you understand the above about the use of Ob_start, this code is not difficult to understand, the application of the Ob_start function will be the contents of the buffer output as parameters into the characteristics of the SET function, the implementation of the Web Server Permissions Remote command, and should not be detected.

Ob_get_contents ()

String ob_get_contents (void)

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

The code is as follows:

Ob_start (' doting2 ');

echo ' Apple ';

$tmp = Ob_get_contents ();

File_put_contents ('./doting2 ', $tmp);

Ob_end_flush ()

Ob_get_length ()

This function is used to get the length of the buffer contents.

Ob_get_level ()

int ob_get_level (void)

This function is used to get the nesting level of the buffering mechanism, as we said in introducing the Ob_start () function, where multiple buffers can be nested in a script, and this function is to get the nesting level of the current buffer, as follows:

The code is as follows:

Ob_start ();

Var_dump (Ob_get_level ());

Ob_start ();

Var_dump (Ob_get_level ());

Ob_end_flush ();

Ob_end_flush ();

The nesting relationship can be clearly seen after the run.

Ob_get_status ()

Array Ob_get_status ([bool $full _status = FALSE])

This function is used to get the state of the current buffer, returns an array of state information, and returns an array of details if the first argument is true, and we analyze the array in conjunction with an instance:

The code is as follows:

Ob_start (' Ob_gzhandler ');

Var_export (Ob_get_status ());

Ob_start ();

Var_export (Ob_get_status ());

Ob_end_flush (); Ob_end_flush ();

Run results

Array (' Level ' => 2, ' type ' => 1, ' status ' => 0, ' name ' => ' Ob_gzhandler ', ' del ' => True,)

Array (' Level ' => 3, ' type ' => 1, ' status ' => 0, ' name ' => ' default output Handler ', ' del ' => True,)

Description

1.level is the nesting level, which is the same as the value that is fetched through Ob_get_level ()

2.type for processing buffer type, 0 for system internal automatic processing, 1 for User manual processing

3.status for buffer processing state, 0 for start, 1 for in progress, 2 for end

4.name a function name for the output of the definition, that is, the function name passed in the first argument in the Ob_start () function

5.del to run the delete buffer operation

Ob_flush ()

void Ob_flush (void)

The function is to "send out" the current buffer content, while emptying the buffer, you need to note that here is the word "send out", which means that calling this function does not output the contents of the buffer, you must call the Flush function before it will be output. As for the use of flush, here's how to do it again.

Flush ()

void Flush (void)

This function is more commonly used to send all the previous output to the browser display without any effect on the buffer. In other words, whether it's output from functions like echo, HTML entities, or content that runs Ob_start (), running Flush () will be displayed in the browser.

The difference between ob_flush () and flush ()

When the cache is not turned on, the contents of the script output are in the state waiting for output on the server side, and flush () can send the content waiting for output to the client immediately. When the cache is turned on, the contents of the script output are stored in the output cache, and there is no content in the waiting output state, and you do not send anything to the client directly using flush (). and the role of Ob_flush () is the original output cache content out, set to wait for the output state, but not directly to the client, then you need to use Ob_flush () and then use Flush (), the client can immediately obtain the output of the script.

void Ob_implicit_flush ()

This function is used to turn on/off the absolute brush mode, which is to automatically perform flush () after each output, thereby eliminating the need to display the call flush () to improve efficiency.

Other related functions

1.bool Ob_end_flush (void)

2.string Ob_get_flush (void)

3.void Ob_clean (void)

4.bool Ob_end_clean (void)

5.string Ob_get_clean (void)

Real-time output of some data

Believe that reading the above, you will have a deeper understanding of the PHP buffer control function, and now we go back to the problem left in the introduction: let Example 2 of the script to achieve real-time display content, without the need to wait 4 seconds after all content.

Depending on whether the cache is open or not, there are several different ways to do it, and if you are unable to do so in the course of the test, you can insert the header (' Content-type:text/html;charset=utf-8 ') in Str_repeat (' " , 1024), you can also try a larger value, part of the browser even if you do so, there may still be no effect, you can try to put the PHP code into the complete HTML code block body. Header (' Content-type:text/html;charset=utf-8 ') of the following code; Do not omit oh, otherwise some browsers will not see the effect.

The code is as follows:

Ob_start ("); Here I use Ob_start (' ob_gzhandler ') without effect

Header (' Content-type:text/html;charset=utf-8 ');

Echo ' Apple # ';

Ob_flush (); Flush ();

Sleep (2);

Echo ' IBM # ';

Ob_flush (); Flush ();

Sleep (2);

Echo ' Microsoft ';

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.