Use of ob _ * series functions

Source: Internet
Author: User
Using PHP to control the user's browser-ob _ * series functions using OutputControl allows you to freely control the data output in the script. It is very useful, especially when you want to output the file header after the data has been output. The output control function does not affect the file header information sent when header () or setcookie () is used. it only applies to the browser-ob _ * series functions that use PHP to control users.

The Output Control function allows you to freely Control the Output of data in the script. It is very useful, especially when you want to output the file header after the data has been output. The output control function does not affect the header information sent using header () or setcookie (). it only applies to data blocks similar to echo () and PHP code. Let's take a simple example to give you a general impression on Output Control:

Example 1.

Ob_start (); // open the buffer echo "Hellon"; // output header ("location: index. php "); // redirect the browser to index. php ob_end_flush (); // output all content to the browser

Anyone who knows about the header () function knows that this function will send a file header to the browser, but if any output (including null output, for example, a blank space, carriage return, or line feed will prompt an error. If we remove ob_start () from the first line and execute this program, we will find an error message: "Header had all ready send "! However, when ob_start is added, no error will be prompted because when the buffer zone is opened, the characters after echo will not be output to the browser, but will be retained on the server until you use flush or ob_end_flush, so there will be no file header output errors!

1. related functions

1. Flush: refresh the buffer content and output it. Function format: flush () Description: This function is frequently used and highly efficient.

2. ob_start: format of the function used to open the output buffer: void ob_start (void) description: When the buffer is activated, all non-file header information from the PHP program is not sent, but saved in the internal buffer zone. To output the buffer area content, you can use ob_end_flush () or flush () to output the buffer area content.

3. ob_get_contents: returns the content of the internal buffer. Usage: string ob_get_contents (void) Description: This function returns the content in the current buffer. if the output buffer is not activated, FALSE is returned.

4. ob_get_length: return the length of the internal buffer. Usage: int ob_get_length (void) Description: This function returns the length of the current buffer. it is the same as ob_get_contents if the output buffer is not activated. Returns FALSE.

5. ob_end_flush: sends the content of the internal buffer to the browser and closes the output buffer. Usage: void ob_end_flush (void) Description: This function sends the content of the output buffer (if any ). 6. ob_end_clean: delete the content of the internal buffer and disable the use of the internal buffer. void ob_end_clean (void): This function will not delete the content of the internal buffer!

7. ob_implicit_flush: How to enable or disable absolute refresh: void ob_implicit_flush ([int flag]) description: Perl users all know the meaning of $ | = x, this string can enable/disable the buffer, while the ob_implicit_flush function is the same as that. by default, the buffer is disabled. after the absolute output is opened, the output of each script is directly sent to the browser without calling flush ()

2. In-depth understanding 1. about the Flush function: This function appears in PHP3, which is a very efficient function. it has a very useful function that is to refresh the browser cache. we will give an example with very obvious running effect to illustrate flush.

Example 2.

For ($ I = 1; $ I <= 300; $ I ++) print (""); // This sentence is critical, the cache structure makes it output from the browser only when the content reaches a certain size. // In other words, if the cache content does not reach a certain size, it will not be output before the program is executed. After a test, I found that the size limit is 256 characters long. This means that the content received by the cache will be sent continuously in the future. For ($ j = 1; $ j <= 20; $ j ++) {echo $ j. ""; flush (); // This part will squeeze out the new content of the cache and display it to the browser sleep (1); // let the program "sleep" for one second, will make you better understand the effect}

The specific effect you can look at here http://www.php2000.com /~ Uchinaboy/out. php PHP2000's latest PHP chat room is using this technology. Unfortunately, the source code is not publicly available.

Note: If you add ob_implicit_flush () to the program header to enable absolute refresh, you can stop using flush () in the program. The advantage of doing this is to improve efficiency!

2. about ob functions: I would like to first reference an example of my good friend y10k:

Example 3.

For example, you can obtain the configuration information of the server and the client, but this information may vary depending on the client. what if you want to save the output of the phpinfo () function? There is no way to control the buffer, but with the control of the buffer, we can easily solve the problem:

Ob_start (); // open the buffer phpinfo (); // use the phpinfo function $ info = ob_get_contents (); // Obtain the buffer content and assign it to $ info $ file = fopen('info.txt ', 'w'); // open the info.txt fwrite ($ file, $ info) file ); // write the information to info.txt fclose ($ file); // Close the info.txt file

With the above method, you can save the phpinfo information of different users. I am afraid there is no way to do this before! In fact, the above is how to convert some "procedures" into "functions! Someone may ask, "is it like this? Is there any other purpose ?" Of course, for example, the PHP syntax highlighted by the Author Forum is related to this (the default PHP syntax highlighted by the display function will be directly output and the results cannot be saved, I am afraid it will be a waste of CPU if it is displayed in every call. in my forum, I will keep the result of the function highlighted by the syntax in the method of controlling the buffer ), if you are interested, you can take a look at the http://www.zphp.com/bbs! You may have some knowledge about the functions of ob_start (). the above example seems simple, but you have mastered the key points of using ob_start.

<1> use ob_start to open the browser cache. This ensures that the cache content will not be output before you call flush (), ob_end_flush () (or after the program is executed.

<2>. now you should know your advantages: you can use header, setcookie, and session after any output content, which is a great feature of ob_start. you can also use the ob_start parameter, after the cache is written, run the command automatically, such as ob_start ("ob_gzhandler"). The most common practice is to use ob_get_contents () to get the content in the cache, and then proceed ......

<3>. after processing is completed, we can use various methods for output, flush (), ob_end_flush (), and automatic output after the program is executed. Of course, if you use ob_get_contents (), you can control the output mode by yourself. Let's see what we can do with ob functions ......

(1) Introduction to static templates: static templates are html pages generated by PHP on the client. If this html page is no longer updated, when another user browses this page again, the program will no longer call PHP and related databases. for some websites with a large amount of information, for example, sina, 163, sohu. The benefits of similar technologies are enormous. I know there are two ways to implement static output:

<1>. use the template. inc. php class modified by y10k to implement phplib.

<2>. use ob functions. For the first method, because it is not a problem to be studied in this article, I will not go into details. Let's take a look at the specific implementation of the second method:

Example 4.

Ob_start (); // open the buffer

All php page output

$ Content = ob_get_contents (); // get all the content output on the php page $ fp = fopen ("output00001. html "," w "); // create a file and open it. prepare to write fwrite ($ fp, $ content); // write the content of the PHP page to output1_1.html, and then ...... Fclose ($ fp );

In this way, the so-called static templates can be easily implemented ......

(2) capture and output the above Example 4. this is the simplest case. you can also operate on $ content before writing ...... You can try to capture some keywords and then process them, such as the PHP syntax highlighted in Example 3. I personally think that this function is the biggest essence of this function. it can solve a variety of problems, but you need to have enough imagination ......

Example 5.

Function run_code ($ code) {If ($ code) {ob_start (); eval ($ code); $ contents = ob_get_contents (); ob_end_clean ();} else {echo "error! No output "; exit ();} return $ contents ;}

The above example is not very useful, but the typical $ code itself is an output page containing variables, and this example uses eval to replace the variables in $ code, then capture the output results and process them again ......

Example 6.Acceleration of transmission

/* ** Title.........: PHP4 HTTP Compression Speeds up the Web ** Version.......: 1.20 ** Author........: catoc 
  ** Filename......: gzdoc.php ** Last changed..: 18/10/2000 ** Requirments...: PHP4 >= 4.0.1 ** PHP was configured with --with-zlib[=DIR] ** Notes.........: Dynamic Content Acceleration compresses ** the data transmission data on the fly ** code by sun jin hu (catoc) 
  ** Most newer browsers since 1998/1999 have ** been equipped to support the HTTP 1.1 ** standard known as "content-encoding." ** Essentially the browser indicates to the ** server that it can accept "content encoding" ** and if the server is capable it will then ** compress the data and transmit it. The ** browser decompresses it and then renders ** the page. ** ** Modified by John Lim (jlim@natsoft.com.my) ** based on ideas by Sandy McArthur, Jr ** Usage........: ** No space before the beginning of the first '
  ** | ** |... the page ... ** | ** |
  ** -------------End of file----------- */ ob_start(); ob_implicit_flush(0); function CheckCanGzip() {         global $HTTP_ACCEPT_ENCODING;         if (headers_sent() || connection_timeout() || connection_aborted()) {                 return 0;         }         if (strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false) return "x-gzip";         if (strpos($HTTP_ACCEPT_ENCODING, 'gzip') !== false) return "gzip";         return 0; } /* $level = compression level 0-9, 0=none, 9=max */ function GzDocOut($level = 1, $debug = 0) {         $ENCODING = CheckCanGzip();         if ($ENCODING) {                 print "n
 n";                 $Contents = ob_get_contents();                 ob_end_clean();                 if ($debug) {                         $s = "

Not compress length: " . strlen($Contents); $s .= "Compressed length: " . strlen(gzcompress($Contents, $level)); $Contents .= $s; } header("Content-Encoding: $ENCODING"); print "x1fx8bx08x00x00x00x00x00"; $Size = strlen($Contents); $Crc = crc32($Contents); $Contents = gzcompress($Contents, $level); $Contents = substr($Contents, 0, strlen($Contents) - 4); print $Contents; print pack('V', $Crc); print pack('V', $Size); exit; } else { ob_end_flush(); exit; } }

This is a piece of code from catoc a long time ago. it was seen in weblogs.com. he used the zlib function to compress the transmitted content. the test shows that for pages larger than 10 KB, the larger the page, the more obvious the effect ......

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.