Use PHP's Ob_start (); Control your browser cache!_php tips

Source: Internet
Author: User
Tags eval file info flush pack php class php code phpinfo strlen
The output control function gives you a free rein in the outputs of the data in the script. It's very useful, especially for: when you want to output the file header after the data has been exported. Output control functions do not use header () or Setcookie (), send header information to affect, only for those similar to echo () and PHP code blocks of data have effect.

Let's start with a simple example that gives you a general impression of output control:
Example 1.

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

All people who know about the header () function know that this function sends a file header to the browser, but if you have any output (including null output, such as a space, a carriage return, or a newline) before using this function, you will be prompted for an error. If we remove the first line of Ob_start () and then execute the program, we will find an error message: "Header had all ready send by"! But with Ob_start, you won't be prompted for an error, because when the buffer is open, the characters behind Echo are not exported to the browser, but remain on the server until you use flush or ob_end_flush to output, so there is no error in the header output!


Introduction of related functions:
1, Flush: Refresh the contents of the buffer, output.
function format: Flush ()
Description: This function is frequently used and highly efficient.
2, Ob_start: Open the output buffer
function format: void Ob_start (void)
Note: When the buffer is activated, all non-file header information from the PHP program is not sent, but is saved in the internal buffer. 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.
Using method: String ob_get_contents (void)
Description: This function returns the contents of the current buffer and FALSE if the output buffer is not active.
4, Ob_get_length: Returns the length of the internal buffer.
How to use: int ob_get_length (void)
Description: This function returns the length of the current buffer, as ob_get_contents if the output buffer is not active. Returns FALSE.
5, Ob_end_flush: Send the contents of the internal buffer to the browser, and turn off the output buffer.
Usage method: 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 method: void Ob_end_clean (void)
Description: This function does not output the contents of the internal buffer but deletes it!
7. Ob_implicit_flush: Turn absolute refresh on or off
How to use: void Ob_implicit_flush ([int flag])
Description: People who have used Perl know the meaning of $|=x, this string can open/close the buffer, and the Ob_implicit_flush function is the same as that, the default is to close the buffer, open absolute output, each script output is sent directly to the browser, no longer need to call the flush ()


Second, in-depth understanding:

1. About the Flush function:
This function appears in the PHP3, is a very efficient function, he has a very useful function is to refresh the browser cache. We give a very obvious example of the effect of the operation to illustrate the flush.
Example 2.

code<?php
for ($i = 1; $i <=; $i + +) print ("");
This sentence is very critical, the cache structure so that its content can only reach a certain size in order to output from the browser
In other words, if the contents of the cache do not reach a certain size, it will not be output before the execution of the program completes. By
After testing, I found that the limit of this size is 256 characters. This means that the content that is received after the cache will
is being sent out in a steady stream.
for ($j = 1; $j <= $j + +) {
echo $j. "
";
Flush (); This one will make the cache new content to be squeezed out, displayed in the browser
Sleep (1); Let the program "Sleep" a second, will make you see the effect more clearly
}
?>


Concrete effect you can come here to see [Url]http://www.php2000.com/~uchinaboy/out.php[/url]
PHP2000 's latest PHP chat room is the technology, unfortunately, the source code is not open L
Note: If the program's first join Ob_implicit_flush () to open absolute Refresh, you can no longer use flush () in the program, the benefit is: improve efficiency!

2. About OB series functions:
I'd like to cite an example of my good friend y10k first:
Example 3.

For example, you use the server and client settings information, but this information will vary depending on the client, what if you want to save the output of the phpinfo () function? Before there is no buffer control, we can say that there is no way, but with the control of the buffer, we can easily solve:
code<?php
Ob_start (); Open buffer
Phpinfo (); Using the Phpinfo function
$info =ob_get_contents (); Gets the contents of the buffer area and assigns 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
?>


Using the above method, can be different users of the Phpinfo information to save, which in the past I am afraid to do! In fact, the above is a number of "process" into the "function" Method!
Someone might ask, "Is this the way it is?" Are there any other uses? "Of course there are, such as the author of the Forum's PHP syntax highlighting is related to this (php default syntax highlighting function will be directly output, can not save the results, if every call will be shown to be very wasteful CPU, the author of the Forum on the syntax highlighting the results of the function of the control buffer to retain the method, If you are interested, you can take a look at [url]http://www.zphp.com/bbs/[/url]!

Maybe now we have a certain understanding of the function of Ob_start (), an example above seems simple, but actually has mastered the use of Ob_start () the main points.
<1&gt. Use Ob_start to open the cache of browser, which guarantees that the contents of the cache will not be output until you call Flush (), Ob_end_flush () (or the program executes).
<2> Now you should know the advantages you have: You can use Header,setcookie and session after any output, which is a great feature of Ob_start, or you can use Ob_start parameters, after the cache is written , and then automate the command, such as Ob_start (\ "Ob_gzhandler\"), and our most common practice is to use ob_get_contents () to get the contents of the cache and then process ...
<3&gt. When finished, we can use various methods to output, flush (), Ob_end_flush (), and then automatically output after the program has finished executing. Of course, if you are using Ob_get_contents (), then you have to control the output mode.

Here, let's see what we can do with the OB series function ...

One, static template technology

Introduction: The so-called static template technology is in some way, so that users get the client side is generated by PHP HTML page. If the HTML page is not updated, then when another user browses to the page again, the program will no longer invoke PHP and the associated database, for some of the more informative sites, such as Sina,163,sohu. The benefits of this kind of technology are enormous.

I know there are two ways to achieve static output:
&LT;1&GT: y10k modified by a phplib called template.inc.php class implementation.
<2> Use the OB series function implementation.
For the first method, because it is not the subject of this article to study, so no longer repeat.
Let's look at the concrete implementation of the second method:
Example 4.


code<?php
Ob_start ()//Open buffer
?>
All output of PHP page
?
$content = ob_get_contents ()//Get all content of 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, and then ...
Fclose ($FP);
?>

In this way, the so-called static template is very easy to be implemented ...

Second, capture output

Above the example 4. is one of the simplest situations where you can also manipulate $content before writing ...
You can try to capture some of the keywords and then go back to it, like Example 3. The PHP syntax is highlighted. Personally, this function is the greatest essence of this function, it can solve a variety of problems, but need you have enough imagination ...
Example 5.

code<?
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 use of this example is not very large, but very typical $code itself is a variable output page, and this example with eval $code variables in the substitution, and then the output of the output capture, again to deal with ...

Example 6. Faster transmission


code<?
/*
* * Title ...: PHP4 HTTP Compression speeds up the Web
* * Version ...: 1.20
* * Author ...: Catoc <[email]catoc@163.net[/email]>
* * Filename ...: gzdoc.php
* * Last changed.: 18/10/2000
* * Requirments ...: PHP4 >= 4.0.1
* * PHP is configured with--with-zlib[=dir]
* * Notes ...: Dynamic Content acceleration Compresses
* * The data transmission data on the fly
* * Code by Sun Jin Hu (catoc) <[email]catoc@163.net[/email]>
* * 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'll then
* * Compress the data and transmit it. The
* * Browser decompresses it and then renders
* * the page.
**
* * Modified by John Lim ([Email]jlim@natsoft.com.my[/email])
* * Based on ideas by Sandy McArthur, Jr
* * Usage ...:
* * No Space before the beginning of the ' the ' the ' <?\ ' tag.
* *------------Start of File----------
* * |&LT;?
** | Include (\ ' gzdoc.php\ ');
** |? >
* * |* * | ... the page ...
* * |* * |&LT;?
** | Gzdocout ();
** |? >
* *-------------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<!--use compress $ENCODING-->n\";
$Contents = Ob_get_contents ();
Ob_end_clean ();
if ($debug) {
$s = \ "<p>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 CATOC a long time code, is seen in Weblogs.com, he took advantage of the zlib function, the transmission of the content of the compression, testing shows that for more than 10k of the page, will produce effects, and the larger the page, the effect is more obvious ...

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.