Common tips: Use PHP to control your browser cache

Source: Internet
Author: User
Tags eval file info flush header pack php class sleep 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
When the data has been exported, the file header is then output. The output control function does not use header () or Setcookie ().
The file header information that is sent affects only those blocks of data that resemble the Echo () and PHP code.

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

Ob_start (); Open buffer
echo "hello\n"; 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 are using the
This function already has any output (including null output, such as a space, carriage return, and linefeed) that prompts for an error. If I
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 echo behind
Characters are not exported to the browser, but are kept on the server until you use flush or ob_end_flush to output the
In order to not have any file header output error!

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 with ob_get_contents, if the output buffer is not excited
Live. 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
Ob_implicit_flush function is the same as that, the default is to close the buffer, open absolute output, each script output is straight
Send to browser, no longer need to call 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 clear example of the effect of the operation to illustrate flush.
Example 2.
---------------------------------------------------------
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
}
?>
-----------------------------------------------------------

Note: If you turn on absolute refresh at the first Ob_implicit_flush () of the program, you can no longer use the flush in the program
(), the advantage of doing so 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, if you want   
to save the output of the phpinfo () function? There is no way to do that without buffer control, but with   
Buffer control, we can easily resolve:   
----------------------------- --------------------------------   
Ob_start ();//Open Buffer    
phpinfo (); Use the Phpinfo function    
$info =ob_get_contents ();//Get the contents of the buffer area and assign to $info   
$file =fopen (' Info.txt ', ' W '); Open the file info.txt   
fwrite ($file, $info);//write information to info.txt   
Fclose ($file); Closes the file info.txt   
?>   
------------------------------------------------- ------------   
Use the above method, you can put different users of the Phpinfo information to save, which in the past I am afraid to do! In fact, the   
face is to convert some "process" to "function" Method!    
Maybe someone would ask, "is that the way it is?" Are there any other uses? "Of course there are, such as the author of the Forum PHP   
Method Highlights and this about (PHP default syntax highlighting function will be directly output, can not save the results, if each   
call will be very wasteful to show the CPU, The author's forum on the syntax highlighting the results of the function of the control buffer with the method of retention   
)  

------------------------------------------------------------
Perhaps now we have a certain understanding of the function of Ob_start (), an example above seems simple, but actually has the palm
Grasped the main points of using Ob_start ().
<1>: Use Ob_start to open browser cache, so that the cache content can be guaranteed when you call flush
(), The Ob_end_flush () (or the execution of the program) is not output until it is finished.
<2> Now you should know the advantages you have: You can use Header,setcookie after any output and
Session, which is ob_start a great feature; You can also use Ob_start parameters, after the cache is written, and then
Automatically run commands, such as Ob_start ("Ob_gzhandler"), and our most common practice is to use ob_get_contents ()
To the contents of the cache and then handle ...
<3>. When finished, we can use various methods to output, flush (), Ob_end_flush (), and wait until the program finishes
The automatic output after completion. 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 in the client side is generated by PHP HTML page
Surface. If the HTML page is not updated again, the program will not call again when another user browses the page
PHP and related databases, for some of the more informative sites, such as Sina,163,sohu. Like this kind of technology band
The benefits of coming are very great.

I know there are two ways to achieve static output:
<1>: 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.

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 biggest essence of this function, it can solve a variety of problems, but need you 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 use of this example is not very large, but very typical $code itself is an output page containing variables, and this example
The sub uses Eval to replace the variable in the $code, then output the output to capture again, again processing ...

Example 6. Faster 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 is 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'll 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 ' the ' the ' * *------------Start of file---------
-
**│**│include (' gzdoc.php ');
**│? >
**│
**│ ... the page ...
**│
**│**│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";
$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 "\x1f\x8b\x08\x00\x00\x00\x00\x00";    
$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 long time Catoc code, is seen in Weblogs.com, he took advantage of the zlib function, the transmission of the inner
Capacity for compression, testing shows that for more than 10k of the page, will produce effects, and the larger the page, the more obvious 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.