PHP page output cache control in-depth analysis

Source: Internet
Author: User
Tags flush html tags ini md5 md5 encryption php script phpinfo sleep


In PHP, the so-called output buffer, is the code in the Echo or other output commands in the execution is written to the PHP buffer, after the script execution or force the output cache command, will output data to the browser (where PHP buffer Is the output_buffering set in PHP.ini, the default is on, which indicates an unlimited size and can be changed to a number to limit size.

Example:


Echo ' www.111cn.net ';
echo ' technology ';
echo ' Share ';

These two echo are inserted sequentially into the buffer, which outputs the data to the browser only if the script completes or enforces the cached output.
If I want to output echo data in real time, see the following code:

Ob_end_flush (); Turn off the PHP cache, or execute Ob_flush () before Flush (), here's an explanation
echo Str_pad ("", 256);
For ($i =5 $i >0; $i-) {
echo $i. ' <br> ';
Flush ();
Sleep (1);
}

Attention:

1:flush and Ob_flush differences:

At first glance the two are very similar, and many manuals are not clear explanation, the model is ambiguous, in fact, there is a big difference between the two.

When PHP.ini does not open the PHP buffer cache, the contents of the PHP script output will be in the server waiting for output state, will not be saved to the output cache, because the cache is not open, At this time, flush can be used to output the content that waits for output immediately to the client (browser or other output).

When PHP.ini opened the PHP buffer cache, the first step of the PHP script output is stored in the output cache, when the output of the content is not data, with flush words is no effect, access to data. So first use Ob_flush to remove the contents of the output cache into the state of waiting for output, and then use the flush to send the content to the client. The order of execution is first Ob_flush and then flush.

Therefore, to achieve real-time output, or use Ob_end_flush first turn off the PHP output cache directly after flush, or first ob_flush flush.

2: The browser is unable to output real-time data

Change the code to the following code, in the Chrome Firefox IE and other browsers are one-time output, very exotic phenomenon:

Ob_end_flush (); Turn off the PHP cache, or Ob_flush () before flush;
echo Str_pad ("", 256);
For ($i =5 $i >0; $i-) {
echo $i;
Flush ();
Sleep (1);
}

Find a half day bug, finally found a phenomenon, as long as the way to add an HTML tag, you can output in real time.
The reason is: only when the HTML tag is encountered in the instant output, it is amazing, fortunately the general output of the content will be with HTML tags, very few plain text.
Workaround: Add a carriage return or other HTML tag to solve the problem.

The following is a detailed description of the related functions of out control

1, flush//will wait for the output of the content sent with the browser, will not affect the buffer.

2, Ob_flush//The contents of the buffer into waiting for the output status, the data has not been exported to the client.

3, Ob_start (callback)//Open the output buffer, you can join the callback callback function, implement the desired function before the output.

Example (1)


Ob_start (' Callbackfun ');
Echo ' 1111111 ';

function Callbackfun ($string) {
return MD5 ($string);//MD5 encryption
}
Results:

1
e10adc3949ba59abbe56e057f20f883e
The result returned by the browser is the encrypted string instead of 1111111, which indicates that the callback function was executed before the data was MD5 encrypted before it was stored in the output cache before it was stored in the output cache.

Example (2)

Combined with Ob_gzhandler to achieve the content of the Web page gzip compression, reduce the size of the transmission, improve the loading speed of the page.


Ob_start (' Ob_gzhandler ');
echo str_repeat (' Hlmblog ', 1024);

The size of the page after Ob_gzhandler is used:

Not using Ob_gzhandler page size

The size of the page becomes much smaller after the obvious compression.

Example (3)

You can nest Ob_start, but remember to have a corresponding closure, two one by one corresponding, or it will be an error, or can not get the data.

Ob_start ();
Var_dump (1);
Ob_start ();
Var_dump (2);
Ob_end_flush ();
Ob_end_flush ();

Results:

int 1
int 2
4, Ob_get_contents () get the content of output buffer or page output

Echo Str_pad (', 1024);//Buffer overflow
Ob_start ()//Open buffer
Phpinfo ();
$content = ob_get_contents ()//Get buffer contents
$f = fopen ('./phpinfo.txt ', ' WB ');/Open File
Fwrite ($f, $content);//content written to TXT file
Fclose ($f);//Close file
Ob_end_clean ()//close buffer, output data and empty browser
Ob_end_flush ()//Send buffer content to client and close buffer, do not empty browser
Attention:

At this time the browser will not output anything, because the use of Ob_end_clean () emptied, but in the current directory will produce a phpinfo.txt file, which is the phpinfo information obtained.

If you use Ob_end_flush, you will not only generate phpinfo.txt files, but also output information in the browser.

5, Ob_get_length () returns the content length of the output buffer

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

6, Ob_get_level ()//Get output buffer nesting level, is the level position


Ob_start ();
Var_dump (Ob_get_level ());
Ob_start ();
Var_dump (Ob_get_level ());
Ob_end_flush ();
Ob_end_flush ();

The browser will output the corresponding level:


int 2
int 3
7, Ob_get_status ()//Get the state of the current buffer, return an array of information


Ob_start (' Ob_gzhandler ');
Var_dump (Ob_get_status ());
Ob_start ();
Var_dump (Ob_get_status ());
Ob_end_flush ();
Ob_end_flush ();

Array
' Level ' => int 2
' Type ' => int 1
' status ' => int 0
' Name ' => string ' Ob_gzhandler ' (length=12)
' Del ' => boolean True
Array
' Level ' => int 3
' Type ' => int 1
' status ' => int 0
' Name ' => string ' default Output handler ' (length=22)
' Del ' => boolean True

Returns an explanation of the array parameters:
Level: Nesting levels, and the values obtained by Ob_get_level () are the same.
Type: Handles buffer type, 0 is system internal automatic processing, 1 is User manual processing.
Status: Buffer processing state, 0 is the beginning, 1 is in progress, 2 is the end.
Name:: The defined output-handling function names are the callback functions of the first parameter in the Ob_start () function.
Del: Whether the delete buffer operation was run.

8, Ob_list_handlers ()//Get the handler function array group, that is, the Ob_start function passed in the first parameter function name


Print_r (Ob_list_handlers ());
Ob_end_flush ();

Ob_start ("Ob_gzhandler");
Print_r (Ob_list_handlers ());
Ob_end_flush ();
The browser outputs a corresponding array of processing function information:


Array ([0] => default output handler) array ([0] => Ob_gzhandler)

9, Ob_implicit_flush ()//turn on or off the absolute brush mode, that is, after each output automatically executed flush (), without corresponding to write multiple flush, save code, improve efficiency


Echo Str_pad (', 1024);//Buffer overflow
Ob_end_flush ();
Ob_implicit_flush (TRUE);//Open Absolute brush send
Echo ' hlmblog</br> ';
Flush ();
Sleep (1);
echo ' Share </br> ';
Flush ();
Sleep (1);
Echo ' Technology </br> ';
browser in real time output below:

Hlmblog
Share
Technology
10, Ob_end_flush ()//Send the contents of the internal buffer to the browser, and turn off the output buffer

11, Ob_end_clean ()//delete the contents of the internal buffer, and close the internal buffer

Two: Control the cache output can be used to do what, a few examples of specific

1: Generate static page

Static page loading speed is fast, this sentence is the truth of the household known, do not request the database, this is how cool things ah.
Here is an example of generating a static page:

Echo Str_pad (', 1024);//Buffer overflow
Ob_start ()//Open buffer
$content = ob_get_contents ()//Get the content of the page output
$f = fopen ('./index.html ', ' W ');
Fwrite ($f, $content);//content written to TXT file
Fclose ($f);
Ob_end_clean ()//clear and close buffer
The legendary static page is so simple to generate.

2: Capture output


function test ($param) {
if ($param) {
Ob_start ();
eval ($param);
$contents = Ob_get_contents ();
Ob_end_clean ();
}else {
Echo ' regrets no output ';
Exit ();
}
return $contents;
}

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.