Home > Backend Development > PHP Tutorial > Use PHP's ob_start; to control your browser cache!

Use PHP's ob_start; to control your browser cache!

WBOY
Release: 2016-07-29 08:36:17
Original
908 people have browsed it

[Reprint] Original address: http://www.itbbs.cn/index.php?showtopic=1074
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 file header information sent using header() or setcookie(), only the data blocks similar to echo() and PHP code.
Let’s give a simple example first to give everyone a general impression of Output Control:
Example 1.

<span><br> <span><?php <BR>ob_start</SPAN><SPAN>(); </SPAN><SPAN>//Open buffer <BR></SPAN><SPAN>echo </SPAN><SPAN>"Hellon"; //Output <BR>header("</SPAN><SPAN>location</SPAN> <SPAN>:</SPAN><SPAN>index</SPAN> <SPAN>.</SPAN><SPAN>php</SPAN><SPAN>"); //Redirect the browser to index.php <BR>ob_end_flush();//Output all the content to the browser <BR>?> <br> </span></span>
Anyone who knows the header() function knows that this function will send a file header to the browser, but if there is any output before using this function (including empty output, such as spaces, carriage returns and line feeds) An error will be prompted. If we remove ob_start() in the first line and then execute this program, we will find that we get an error message: "Header had all ready send by"! But with ob_start, there will be no error message. The reason is that when the buffer is opened, the characters after echo will not be output to the browser, but will be retained on the server. They will not be output until you use flush or ob_end_flush, so it will not Any file header output errors!
1. Introduction to related functions:
1. Flush: refresh the contents of the buffer and output.
Function format: flush()
Description: This function is frequently used and is very efficient.
2. ob_start: Open the output buffer
Function format: void ob_start(void)
Description: When the buffer is activated, all non-file header information from the PHP program will not be sent, but will be saved in the internal buffer. In order to output the contents of the buffer, you can use ob_end_flush() or flush() to output the contents of the buffer.
3, ob_get_contents: Return the contents of the internal buffer.
Usage: string ob_get_contents(void)
Description: This function will return the contents of the current buffer. If the output buffer is not activated, it will return FALSE.
4. ob_get_length: Returns the length of the internal buffer.
Usage: int ob_get_length(void)
Description: This function will return the length in the current buffer; like ob_get_contents, if the output buffer is not activated. then returns FALSE.
5. ob_end_flush: Send the contents of the internal buffer to the browser and close the output buffer.
Usage: void ob_end_flush(void)
Description: This function sends the contents of the output buffer (if any).
6. ob_end_clean: Delete the contents of the internal buffer and close the internal buffer.
Usage: void ob_end_clean(void)
Explanation: This function will not output the contents of the internal buffer but delete it!
7. ob_implicit_flush: Turn on or off absolute flush
Usage method: void ob_implicit_flush ([int flag])
Note: Anyone who has used Perl knows the meaning of $|=x. This string can open/close the buffer, and The ob_implicit_flush function is the same as that one. The default is to close the buffer. After turning on absolute output, each script output is sent directly to the browser, and there is no need to call flush().
Second, in-depth understanding:
1. About the Flush function:
This function has appeared in PHP3 and is a very efficient function. It has a very useful function of refreshing the browser's cache. Let's give an example with a very obvious operating effect to illustrate flush.
Example 2.
<span><br><span><?php <BR>$i</span><span>++ ) print (</span><span>" "</span><span>); </span><span></span>// This sentence is very critical. The structure of the cache makes it so that its content can only be output from the browser when it reaches a certain size. <span>// In other words, if the content of the cache does not reach a certain size, The size will not be output before the program execution is completed. After </span>// testing, I found that the lower limit of this size is 256 characters long. This means that the content received by the cache in the future will <span>// be sent out continuously. </span><span></span>For(<span></span>$j <span></span>= <span></span>1<span></span>; <span></span>$j <span><br><= </SPAN><SPAN>20<BR><BR>; <BR><BR>$j</SPAN><SPAN>++) { </SPAN>echo <SPAN></SPAN>$j<SPAN> </SPAN>.<SPAN></SPAN>" <SPAN>"</SPAN><SPAN>; </SPAN><SPAN></SPAN>flush<SPAN></SPAN>(); <SPAN></SPAN>//This part will squeeze out the new content from the cache and display it on the browser <SPAN></SPAN><SPAN>sleep<BR></SPAN>(<SPAN> </SPAN>1<SPAN></SPAN>); <SPAN><BR>//Let the program "sleep" for a second, which will allow you to see the effect more clearly </SPAN><SPAN><BR>} </SPAN><SPAN></SPAN>?><span> </span><span><br></span><br>Note: If you add ob_implicit_flush() to the beginning of the program to turn on absolute refresh, you can no longer use flush() in the program. The advantage of this is: improve efficiency! <br>2. Regarding the ob series functions: <br>I would like to quote an example from my good friend y10k first: <br>Example 3. <br>For example, you can use the setting information of the server and the client, but this information will be different depending on the client. If What should I do if I want to save the output of the phpinfo() function? Before there was no buffer control, it can be said that there was no solution at all, but with buffer control, we can easily solve it: <br><div class="code"> <code><span><br><span><?php <BR>ob_start</SPAN><SPAN>(); </SPAN><SPAN>//Open Buffer <BR></SPAN><SPAN>phpinfo</SPAN><SPAN>(); </SPAN><SPAN>//Use phpinfo function <BR></SPAN><SPAN>$info</SPAN><SPAN>=</SPAN><SPAN>ob_get_contents</SPAN><SPAN>(); </SPAN><SPAN>//Get the contents of the buffer and assign it to $info <BR> </SPAN> <SPAN>$file</SPAN><SPAN>=</SPAN><SPAN>fopen</SPAN><SPAN>('</SPAN><SPAN>info.txt</SPAN><SPAN>'</SPAN><SPAN>,</SPAN><SPAN>'</SPAN><SPAN>w</SPAN><SPAN>'</SPAN><SPAN>); //Open file info.txt <BR>fwrite( $file, $info); //Write information to info.txt <BR>fclose($file); //Close the file info.txt <BR>?> <br></span></span>
Using the above method, you can put the phpinfo information of different users Save it, I’m afraid this was impossible to do before! In fact, the above is a method to convert some "processes" into "functions"!
Some people may ask: "Is it just like this? Are there other uses?" Of course, there is, for example, the PHP syntax highlighting in the author's forum is related to this (PHP's default syntax highlighting function will output directly, The result cannot be saved. If it is displayed every time it is called, it will be a waste of CPU. The author's forum retains the result displayed by the syntax highlighting function by controlling the buffer). If you are interested, you can take a look at http: //www.zphp.com/bbs/!
Maybe now you have a certain understanding of the function of ob_start(). The above example seems simple, but in fact you have mastered the key points of using ob_start().
<1>. Use ob_start to open the browser's cache. This ensures that the contents of the cache will not be output before you call flush(), ob_end_flush() (or the program is executed).
<2>. Now you should know the advantages you have: you can use header, setcookie and session after any output content, which is a great feature of ob_start; you can also use the parameters of ob_start to be written in the cache After entering, then automatically run the command, such as ob_start("ob_gzhandler"); and our most commonly used method is to use ob_get_contents() to get the contents in the cache, and then process it...
<3>. When the processing is completed, We can use various methods to output, flush(), ob_end_flush(), and automatic output after the program is executed. Of course, if you are using ob_get_contents(), then you have to control the output method yourself.
Come on, let’s see what we can do with the ob series functions...
1. Static template technology
Introduction: The so-called static template technology is to use a certain method to enable users to get html pages generated by PHP on the client side. . If this HTML page will no longer be updated, then 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, such as sina, 163, sohu. The benefits of technology like this are huge.
There are two ways to achieve static output that I know of:
<1>. Implemented through a class called template.inc.php of phplib modified by y10k.
<2>. Implemented using ob series functions.
For the first method, because it is not the issue to be studied in this article, I will not go into details.
Let’s now take a look at the specific implementation of the second method:
Example 4.
<span><br><span><?php <BR>ob_start</SPAN><SPAN>();</SPAN><SPAN>//Open the buffer <BR></SPAN><SPAN>?></span> <br>All output of php page <br><span><? <BR>$content </SPAN><SPAN>= </SPAN><SPAN>ob_get_contents</SPAN><SPAN>();</SPAN><SPAN>//Get all content of php page output <BR></SPAN><SPAN>$fp </SPAN><SPAN>= </SPAN><SPAN>fopen </SPAN><SPAN>( </SPAN><SPAN>"output00001.html"</SPAN><SPAN>, </SPAN><SPAN>"w"</SPAN><SPAN>); </SPAN><SPAN>//Create a file and open it, ready to write <BR></SPAN><SPAN>fwrite</SPAN><SPAN>(</SPAN><SPAN>$fp</SPAN><SPAN>, </SPAN> <SPAN>$ content</SPAN><SPAN>); </SPAN><SPAN>//Write all the content of the php page into output00001.html, and then... <BR></SPAN><SPAN>fclose</SPAN><SPAN>(</SPAN><SPAN>$fp</SPAN><SPAN>); <BR></SPAN><SPAN>?></span> <br></span>
2. Capture output
The above Example 4. is the simplest case. You can also operate on $content before writing...
You can try to capture some keywords and then reprocess it. For example, the PHP syntax highlighting described in Example 3. Personally, I think this function is the best part of this function. It can solve a variety of problems, but it requires you to have enough imagination...
Example 5.
<span><br><span><? <BR></SPAN><SPAN>Function </SPAN><SPAN>run_code</SPAN><SPAN>(</SPAN><SPAN>$code</SPAN><SPAN>) { <BR>If(</SPAN><SPAN>$code</SPAN><SPAN>) { <BR></SPAN><SPAN>ob_start</SPAN><SPAN>(); <BR>eval(</SPAN><SPAN>$code</SPAN> <SPAN>); <BR></SPAN><SPAN>$contents </SPAN><SPAN>= </SPAN><SPAN>ob_get_contents</SPAN><SPAN>(); <BR></SPAN><SPAN>ob_end_clean</SPAN><SPAN>(); <BR>}else { <BR>echo </SPAN><SPAN>"Error! No output"</SPAN><SPAN>; <BR>exit(); <BR>} <BR>return </SPAN><SPAN>$contents </SPAN><SPAN>; <BR>} <BR></SPAN></SPAN>


The above example is not very useful, but it is typical that $code itself is an output page containing variables. In this example, eval is used to replace the variables in $code, and then the output results are captured again. Process...
Example 6. 加快传输
<SPAN><BR><SPAN><?  <BR></SPAN><SPAN>/*  <BR>** Title.........: PHP4 HTTP Compression Speeds up the Web  <BR>** Version.......: 1.20  <BR>** Author........: catoc <[email]catoc@163.net[/email]>  <br>** Filename......: gzdoc.php  <br>** Last changed..: 18/10/2000  <br>** Requirments...: PHP4 >= 4.0.1  <br>** PHP was configured with --with-zlib[=DIR]  <br>** Notes.........: Dynamic Content Acceleration compresses  <br>** the data transmission data on the fly  <br>** code by sun jin hu (catoc) <[email]catoc@163.net[/email]>  <br>** Most newer browsers since 1998/1999 have  <br>** been equipped to support the HTTP 1.1  <br>** standard known as "content-encoding."  <br>** Essentially the browser indicates to the  <br>** server that it can accept "content encoding"  <br>** and if the server is capable it will then  <br>** compress the data and transmit it. The  <br>** browser decompresses it and then renders  <br>** the page.  <br>**  <br>** Modified by John Lim ([email]jlim@natsoft.com.my[/email])  <br>** based on ideas by Sandy McArthur, Jr  <br>** Usage........:  <br>** No space before the beginning of the first '<?' tag.  <BR>** ------------Start of file----------  <BR>** |<?  <BR>** | include('gzdoc.php');  <BR>** |? >  <br>** |<HTML>  <br>** |... the page ...  <br>** |</HTML>  <br>** |<?  <BR>** | gzdocout();  <BR>** |? >  <br>** -------------End of file-----------  <br>*/  <br></span><span>ob_start</span><span>();  <br></span><span>ob_implicit_flush</span><span>(</span><span>0</span><span>);  <br>function </span><span>CheckCanGzip</span><span>(){  <br>global </span><span>$HTTP_ACCEPT_ENCODING</span><span>;  <br>if (</span><span>headers_sent</span><span>() || </span><span>connection_timeout</span><span>() || </span><span>connection_aborted</span><span>()){  <br>return </span><span>0</span><span>;  <br>}  <br>if (</span><span>strpos</span><span>(</span><span>$HTTP_ACCEPT_ENCODING</span><span>, '</span><span>x-gzip</span><span>'</span><span>) !== false) return "x-gzip";  <br>if (strpos($HTTP_ACCEPT_ENCODING,</span><span>'</span><span>gzip</span><span>'</span><span>) !== false) return "gzip";  <br>return 0;  <br>}  <br>/* $level = compression level 0-9, 0=none, 9=max */  <br>function GzDocOut($level=1,$debug=0){  <br>$ENCODING = CheckCanGzip();  <br>if ($ENCODING){  <br>print "n<!-- Use compress $ENCODING -->n";  <br>$Contents = ob_get_contents();  <br>ob_end_clean();  <br>if ($debug){  <br>$s = "<p>Not compress length: ".strlen($Contents);  <br>$s .= "  <br>Compressed length: ".strlen(gzcompress($Contents,$level));  <br>$Contents .= $s;  <br>}  <br>header("Content-Encoding: $ENCODING");  <br>print "x1fx8bx08x00x00x00x00x00";  <br>$Size = strlen($Contents);  <br>$Crc = crc32($Contents);  <br>$Contents = gzcompress($Contents,$level);  <br>$Contents = substr($Contents, 0, strlen($Contents) - 4);  <br>print $Contents;  <br>print pack(</span><span>'</span><span>V</span><span>'</span><span>,$Crc);  <br>print pack(</span><span>'</span><span>V</span><span>'</span><span>,$Size);  <br>exit;  <br>}else{  <br>ob_end_flush();  <br>exit;  <br>}  <br>}  <br>?>  <br></span></span>
This is a very old piece of code from catoc, which I saw on weblogs.com. It uses zlib functions to compress the transmitted content. Tests show that it will have an effect on pages of more than 10k, and The larger the page, the more obvious the effect...

The above has introduced the use of PHP's ob_start; to control your browser cache!, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template