"Go" php buffers output_buffering and Ob_start

Source: Internet
Author: User
Tags file info phpinfo setcookie vars drupal

Original: http://blog.csdn.net/21aspnet/article/details/7389427

PHP buffers Output_buffering and Ob_startbuffer

Buffer is a memory address space, the Linux system default size is generally 4096 (4KB), that is, a memory page. It is primarily used to store data between devices that are out of sync or between devices with different priority levels. By using buffer, you can make the process less of a mutual wait. Here is a popular example, when you open a text editor to edit a file, when you enter a character, the operating system does not immediately write this character directly to the disk, but the first write to buffer, when the buffer is filled with a buffer, the data will be written to disk, Of course, when the kernel function flush () is called, it is mandatory to write the dirty data in buffer back to disk.

Similarly, when executing a echo,print, the output is not immediately displayed via TCP to the client browser, but instead writes the data to PHP buffer. The PHP output_buffering mechanism means that a new queue is established before the TCP buffer, and the data must pass through the queue. When a PHP buffer is full, the script process will send the output data from PHP buffer to the system kernel to be displayed by TCP to the browser. So, the data will be written to these places echo/pring. PHP Buffer---browser

PHP output_buffering

By default, PHP buffer is turned on, and the default value of this buffer is 4096, which is 4kb. You can find the output_buffering configuration in the php.ini configuration file. The output data is written to the PHP output_buffering when the user data is Echo,print, until Output_ Buffering is full, this data will be transmitted via TCP to the browser display. You can also manually activate the PHP output_buffering mechanism through Ob_start (), so that even if the output exceeds 4KB data, it does not really give the data to TCP to the browser, because Ob_start () set the PHP buffer space to large enough. Data is sent to the client browser only until the script finishes, or when the Ob_end_flush function is called.

1. When output_buffering=4096, and output less data (less than one buffer)

[PHP]View PlainCopy
    1. <?php
    2. for ($i = 0; $i < 10; $i + +) {  
    3. Echo $i.  ' <br/> ';
    4. Sleep ($i + 1); //  
    5. }
    6. ?>


Phenomenon: Not every few seconds there will be intermittent output, but until the end of the response, in order to see the output at once, wait until the end of the server script processing, the browser interface remains blank. This is because the amount of data is too small and PHP output_buffering is not full. The order in which the data is written, in turn echo->php buffer->tcp buffer->browser

2. When output_buffering=0, and output less data (less than one buffer)

[PHP]View PlainCopy
  1. <?php
  2. Through Ini_set (' output_buffering ', 0) does not take effect
  3. You should edit/etc/php.ini, set output_buffering=0 disable output buffering mechanism
  4. Ini_set (' output_buffering ', 0); Completely disable the output buffering feature
  5. for ($i = 0; $i < 10; $i + +) {  
  6. Echo $i.  ' <br/> ';
  7. Flush (); //Notify the operating system of the underlying, as soon as possible data to the client browser
  8. Sleep ($i + 1); //  
  9. }
  10. ?>


Phenomenon: Inconsistent with the display just now, after disabling the PHP buffering mechanism, the browser can intermittently see the intermittent output, do not have to wait until the completion of the script to see the output. This is because the data is not stuck in PHP output_buffering. The order in which the data is written is Echo->tcp Buffer->browser

3. When output_buffering=4096., output data is greater than one buffer, do not call Ob_start ()

#//Create a 4kb size file $dd if=/dev/zero of=f4096 bs=4096 count=1
[PHP]View PlainCopy
    1. <?php
    2. for ($i = 0; $i < 10; $i + +) {  
    3. echo file_get_contents ('./f4096 '). $i.  ' <br/> ';
    4. Sleep ($i + 1);
    5. }
    6. ?>


Symptom: The response is not over (the HTTP connection is not turned off), intermittent output is visible, and the browser interface does not remain blank. Although the PHP output_buffering mechanism is enabled, it still intermittently outputs, rather than a one-time output, because output_buffering space is not enough. With each PHP buffering, the data is sent to the client browser.

4. When output_buffering=4096, the output data is greater than a TCP buffer, call Ob_start ()

[PHP]View PlainCopy
    1. <?php
    2. Ob_start (); //Open PHP buffer
    3. for ($i = 0; $i < 10; $i + +) {  
    4. echo file_get_contents ('./f4096 '). $i.  ' <br/> ';
    5. Sleep ($i + 1);
    6. }
    7. Ob_end_flush ();
    8. ?>


Phenomenon: Until the server end of the script processing completed, the response is finished, only to see the full output, the time interval is very short, so that you do not feel the pause. Before the output, the browser kept a blank interface, waiting for server data. This is because, once PHP calls the Ob_start () function, it expands PHP buffer to be large enough to send the data in PHP buffer to the client browser until the Ob_end_flush function call or the script runs at the junction speed.

tcpdump observation

Here, we monitor TCP messages through tcpdump to see the difference between using Ob_start () and not using it.
1. No use of Ob_start ()

[Plain]View PlainCopy
  1. 12:30:21.499528 IP 192.168.0.8.webcache > 192.168.0.28.cymtec-port:. ACK 485 win 6432
  2. 12:30:21.500127 IP 192.168.0.8.webcache > 192.168.0.28.cymtec-port:. 1:2921 (2920) ACK 485 win 6432
  3. 12:30:21.501000 IP 192.168.0.8.webcache > 192.168.0.28.cymtec-port:. 2921:7301 (4380) ACK 485 win 6432
  4. 12:30:21.501868 IP 192.168.0.8.webcache > 192.168.0.28.cymtec-port:p 7301:8412 (1111) Ack 485 win 643
  5. 12:30:24.502340 IP 192.168.0.8.webcache > 192.168.0.28.cymtec-port:. 8412:14252 (5840) ACK 485 win 6432
  6. 12:30:24.503214 IP 192.168.0.8.webcache > 192.168.0.28.cymtec-port:. 14252:15712 (1460) ACK 485 win 6432
  7. 12:30:24.503217 IP 192.168.0.8.webcache > 192.168.0.28.cymtec-port:p 15712:16624 (912) Ack 485 win 6432
  8. 12:30:31.505934 IP 192.168.0.8.webcache > 192.168.0.28.cymtec-port:. 16624:23924 (7300) Ack 485 win 6432
  9. 12:30:31.506839 IP 192.168.0.8.webcache > 192.168.0.28.cymtec-port:p 23924:24836 (912) Ack 485 win 6432
  10. 12:30:42.508871 IP 192.168.0.8.webcache > 192.168.0.28.cymtec-port:. 24836:32136 (7300) Ack 485 win 6432
  11. 12:30:42.509744 IP 192.168.0.8.webcache > 192.168.0.28.cymtec-port:p 32136:33048 (912) Ack 485 win 6432
  12. 12:30:57.512137 IP 192.168.0.8.webcache > 192.168.0.28.cymtec-port:. 33048:40348 (7300) Ack 485 win 6432
  13. 12:30:57.513016 IP 192.168.0.8.webcache > 192.168.0.28.cymtec-port:p 40348:41260 (912) Ack 485 win 6432
  14. 12:31:06.513912 IP 192.168.0.8.webcache > 192.168.0.28.cymtec-port:p 41260:41265 (5) ACK 485 win 6432
  15. 12:31:06.514012 IP 192.168.0.8.webcache > 192.168.0.28.cymtec-port:f 41265:41265 (0) Ack 485 win 6432
  16. 12:31:06.514361 IP 192.168.0.8.webcache > 192.168.0.28.cymtec-port:. ACK 486 win 6432

2. Using the Ob_start ()

[Plain]View PlainCopy
  1. 12:36:06.542244 IP 192.168.0.8.webcache > 192.168.0.28.noagent:. ACK 485 win 6432
  2. 12:36:51.559128 IP 192.168.0.8.webcache > 192.168.0.28.noagent:. 1:2921 (2920) ACK 485 win 6432
  3. 12:36:51.559996 IP 192.168.0.8.webcache > 192.168.0.28.noagent:. 2921:7301 (4380) ACK 485 win 6432
  4. 12:36:51.560866 IP 192.168.0.8.webcache > 192.168.0.28.noagent:. 7301:11681 (4380) ACK 485 win 6432
  5. 12:36:51.561612 IP 192.168.0.8.webcache > 192.168.0.28.noagent:. 11681:16061 (4380) ACK 485 win 6432
  6. 12:36:51.561852 IP 192.168.0.8.webcache > 192.168.0.28.noagent:. 16061:20441 (4380) ACK 485 win 6432
  7. 12:36:51.562479 IP 192.168.0.8.webcache > 192.168.0.28.noagent:. 20441:24821 (4380) ACK 485 win 6432
  8. 12:36:51.562743 IP 192.168.0.8.webcache > 192.168.0.28.noagent:. 24821:29201 (4380) ACK 485 win 6432
  9. 12:36:51.562996 IP 192.168.0.8.webcache > 192.168.0.28.noagent:. 29201:33581 (4380) ACK 485 win 6432
  10. 12:36:51.563344 IP 192.168.0.8.webcache > 192.168.0.28.noagent:p 33581:35041 (1460) ACK 485 win 6432
  11. 12:36:51.563514 IP 192.168.0.8.webcache > 192.168.0.28.noagent:. 35041:36501 (1460) ACK 485 win 6432
  12. 12:36:51.563518 IP 192.168.0.8.webcache > 192.168.0.28.noagent:. 36501:37961 (1460) ACK 485 win 6432
  13. 12:36:51.563523 IP 192.168.0.8.webcache > 192.168.0.28.noagent:. 37961:39421 (1460) ACK 485 win 6432
  14. 12:36:51.563526 IP 192.168.0.8.webcache > 192.168.0.28.noagent:. 39421:40881 (1460) ACK 485 win 6432
  15. 12:36:51.563529 IP 192.168.0.8.webcache > 192.168.0.28.NOAGENT:FP 40881:41233 (352) ACK 485 win 6432
  16. 12:36:51.570364 IP 192.168.0.8.webcache > 192.168.0.28.noagent:. ACK 486 win 6432

From the above comparison, we can see that the time interval of the data message is obviously different. Not using Ob_start (), the time interval is relatively large, waiting for about 4 seconds to send the data in the TCP buffer. Data is not in PHP buffer for too long, the output data is sent to the client browser. That's because, soon enough, PHP buffer was full and had to send the data out. When Ob_start () is enabled, it is different, sending packets to the client, which is sent almost at the same time. This makes it possible to infer that the data has been in PHP buffer until the Ob_end_flush () is called to send the data in PHP buffer to the client browser.

Output buffering function

1.ob_start
Activates the output_buffering mechanism. Once activated, the script output is no longer directed to the browser, but is temporarily written to the PHP buffer memory area.

PHP opens the output_buffering mechanism by default, except that by calling the Ob_start () function The output_buffering value is extended to large enough. You can also specify $chunk_size to specify the value of Output_buffering. The default value of $chunk _size is 0, which means that data in PHP buffer is not sent to the browser until the end of the script run. If you set the size of the $chunk_size, the data in buffer is sent to the browser as long as the data length in the buffer reaches that value.

Of course, you can work with the data in buffer by specifying $ouput_callback. For example, function Ob_gzhandler, compress the data in buffer and then pass it to the browser.

2.ob_get_contents
Get a copy of the data in PHP buffer. It is worth noting that you should call this function in the Ob_end_clean () function call, otherwise ob_get_contents () returns an empty character.

3.ob_end_flush and Ob_end_clean
These two functions are a bit similar and will close the ouptu_buffering mechanism. But the difference is that Ob_end_flush simply flushes the data in PHP buffer (flush/send) to the client browser, and Ob_clean_clean empties the data in PHP bufeer (erase), but does not send it to the client browser. After the Ob_end_flush call, the data in PHP buffer still exists, and ob_get_contents () can still get a copy of the data in PHP buffer. After the Ob_end_clean () call, Ob_get_contents () takes an empty string, and the browser receives no output, that is, no output.

Usage Cases

often see Ob_start () used in some template engine and page file caches. In the well-known open source project Wordpress,drupal,smarty and other places, can find their shadow. The application of Drupal is drawn here.

#模板文件

@file:user-profile.tpl.php<div>     <ul>          $user,name? ></li > <li>picture:picture?></li> </ul></div>//@file: $user template-render.php       
[PHP]View PlainCopy
  1. <?php
  2. function theme_render_template ($template _file, $variables) {
  3. if (! Is_file ($template _file) { return "";}
  4. Extract ($variables, Extr_skip);
  5. Ob_start ();
  6. $contents = ob_get_contents ();
  7. Ob_end_clean ();
  8. return $contents;
  9. }
  10. ?>

@file:p rofile.php
[PHP]View PlainCopy
    1. <?php
    2. $variables = Array (' user ' = = $user);
    3. Print theme_render_template (' user-profile.tpl.php ', $variables);
    4. ?>

----------------------------

<?php
Ob_start ();
Setcookie ("username", "AAA", Time () +3600);
echo "The username is:". $HTTP _cookie_vars["username"]. " \ n ";
echo "The username is:". $_cookie["username"]. " \ n ";
Print_r ($_cookie);
?>
Warning:cannot Modify header Information-headers already sent by error reason
I added the header to the PHP program,
Header ("Cache-control:no-cache,must-ridate");
After the page appears above the error, read n data also has no results.

Today occasionally found that the original is my php.ini inside the configuration out of the problem, find php.ini file
The output_buffering default is off. I'm going to set it to 4096 now OK.
Used to resolve display prompt error, cannot press (date + export file number) to file name error message.
The Setcookie function must be sent out before any information is delivered to the browser.
Based on these limitations, so the Setcookie () function is executed.

Often encounter "Undefined index",

"Cannot modify header Information-headers already sent by" ... and other questions,

To resolve the "cannot modify header Information-headers already sent by" This is the wrong way to produce a cookie before the cache is extended to the browser,

Therefore, you can add Ob_start () to the front of the program, and this function.
The Ob_start () function is used to open the buffer, such as the header () function, if there is output, including carriage return \ space \ newline \ will have "Header had all ready to send by" error, you can first use Ob_start () The data Block and Echo () output that open the buffer PHP code will go into the buffer without immediately outputting it. Of course, opening the buffer is a lot of work, just play your imagination. You can summarize the following four points:

1. Before header ()

Ob_start (); Open buffer
echo \ "Hellon\"; Output
Header ("location:index.php"); redirect the browser to index.php
Ob_end_flush ();//output all content to the browser
?>

The 2.phpinfo () function obtains information on both the client and server side, but the way to save the client information with buffers is the best choice.
Ob_start (); Open buffer
Phpinfo (); Using the Phpinfo function
$info =ob_get_contents (); Get the contents of the buffer area and assign it to $info
$file =fopen (\ ' info.txt\ ', \ ' w\ '); Open File Info.txt
Fwrite ($file, $info); Write information to Info.txt
Fclose ($file); Close File Info.txt
?>

3. Static page Technology
Ob_start ();//Open buffer
?>
Full output of PHP page
$content = Ob_get_contents ();//Get all the contents of the PHP page output
$fp = fopen ("output00001.html", "w"); Create a file, and open it, ready to write
Fwrite ($fp, $content); Write the contents of the PHP page to output00001.html, then ...
Fclose ($FP);
?>

4. Output code
Function Run_code ($code) {
If ($code) {
Ob_start ();
($code);
$contents = Ob_get_contents ();
Ob_end_clean ();
}else {
echo "Error! No output ";
Exit ();
}
return $contents;
}

"Go" php buffers output_buffering and Ob_start

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.