Tips for caching and compressing dynamic pages in PHP

Source: Internet
Author: User
Tags crc32 xslt
Mod_gzip is an Apache module whose function is to compress static HTML pages using gzip, and the browser that adheres to the IETF standard can accept gzip encoding (IE, Netscape, etc.). Mod_gzip can increase the download time of the page by up to 4-5 times. I strongly recommend that you use Mod_gzip on your Web server. However, we also have to build our own compression engine with PHP. In this article, I'm going to show you how to use the output control functions of PHP to dramatically speed up page loading.

Introducing the output control function of PHP

The most satisfying thing about PHP4 is that you can have PHP cache all the output generated by the script and the browser will not receive anything until you decide to send them out. In the script you can use these functions to set the header, cookies, but this is only a small part of the powerful output function.

<?php void Ob_start (void);?>

Tell the PHP processor to redirect all output to an internal cache (buffer). No output will be sent to the browser until the Ob_start is called.

<?php string ob_get_contents (void);?>

The function returns the output buffer as a string. You can call this function to send the accumulated output to the browser. (only after turning the buffering function off!!) )

<?php int ob_get_length (void);?>

Returns the length of the string in the cache.

<?php void Ob_end_clean (void);?>

Clears the output cache and closes the output cache. This function must be used before the contents of the cache are exported to the browser.
void 501 ([int flag])
Used to turn on/off the implied flush action switch (off by default). If flush is on, the output is immediately sent to the browser, each time a print/echo or other output command is called.

Use output control to compress PHP output
You must compress the output using the zlib extension package compiled in PHP4. You can view the installation instructions for the zlib package in the PHP documentation, if necessary.
First, initialize the output cache:

<?php Ob_start (); Ob_implicit_flush (0);?>

Then, use print, echo, or any other method you like to generate all the output, such as:

<?phpprint ("Hey This is a compressed output!"); ?>

After the page is generated, we retrieve the output:

<?php $contents = ob_get_contents (); Ob_end_clean ();?>

After that, you must detect whether the browser supports compressing the data. If supported, the browser will send a accept-encodeing HTTP header to the server side. We just need to check if there is a "gzip,deflate" string in the $http_accept_encoding variable.

<?php if (ereg (' gzip, deflate ', $HTTP _accept_encoding)) {//Generate gzip compressed content here} else {echo $contents;}?>

This method is simple to use and clearly structured. Let's look at how to generate the compressed output:

<?php//Tell the browser to receive the GZIP data//Of course, before you have checked whether they support the Gzip,x-gzip data format//If support is X-gzip, then the following header will use Z-gzip instead of the header (" Content-encoding:gzip ");//Display the gzip file header//Only one time to display the echo" x1fx8bx08x00x00x00x00x00 ";//calculate the file size and CRC code $Size = strlen ($ Contents); $CRC = CRC32 ($contents);//Compressed Data $contents = gzcompress ($contents, 9);//We cannot output this, because CRC code is chaotic. If I use "echo $contents" here, the compressed data will be sent,//But not complete. The last four bytes of the file are CRC checksums, but only three bytes are emitted. The last byte was discarded. I don't know if this bug was fixed in version 4.0.2,//But the best way to avoid errors is to add the correct CRC checksum to the end of the compressed data. Stripping the old CRC checksum $contents = substr ($contents, 0, strlen ($contents)-4);//Display only compressed data echo $contents;//Output CRC, and original data size (bytes) g Zip_printfourchars ($CRC);  Gzip_printfourchars ($Size), function Gzip_printfourchars ($Val) {for ($i = 0; $i <4; $i + +) {echo chr ($Val%); $Val = Floor ($Val/256); }}?>//Well, you can also attach more compressed data in this way.

To perform the actual test, all the script code is as follows:

<?php Ob_start (); Ob_implicit_flush (0);p rint ("I ' m compressed!n"); $contents = Ob_get_contents (); Ob_end_clean (), Header ("Content-encoding:gzip"), echo "x1fx8bx08x00x00x00x00x00", $Size = strlen ($contents);  $CRC = CRC32 ($contents); $contents = Gzcompress ($contents, 9); $contents = substr ($contents, 0, strlen ($contents)-4); Echo $contents; Gzip_printfourchars ($CRC);  Gzip_printfourchars ($Size), function Gzip_printfourchars ($Val) {for ($i = 0; $i <4; $i + +) {echo chr ($Val%); $Val = Floor ($Val/256); }}?>

Cache PHP Output

When PHP4 was not available and I had to use PHP3, I was interested in developing some caching mechanisms to reduce database loading and file system access. There is nothing particularly good in PHP3, but with the output cache, everything becomes much easier in PHP4.
Here's a simple example:

<?php//Constructs a file name for the requested URI $cached _file=md5 ($REQUEST _uri); if (!file_exists ("/cache/$cached _file") | | (!is_valid ("/cache/$cached _file"))) {The//is_valid function validates the cache, and you can use this function to check if the caches are out of date or other specific conditions. Generates output Ob_start () if the file is not in the cache or is not available; Ob_implicit_flush (0); In this output ... $contents = Ob_get_contents (); Ob_end_clean (); $fil =fopen ($cached _file, "w+"); Fwrite ($fil, $contents, $strlen ($contents)); Fclose ($fil); }/If the requested file is in the cache and is available, then: ReadFile ($cached _file); >

This is a simple example, using output caching, you can build a complex content generation system, use different caching mechanisms for different blocks or programs, and so on ...

Conclusion

The PHP output control function is useful for redirecting script-generated output to the cache. You can reduce the load time by outputting cached data for browsers that support Gzip. It can also be used as a caching mechanism to reduce access to data sources (databases or files), which is significant for using XML.
If we build an engine with PHP, cache the data from the data source (XML documents and databases), and dynamically generate XML-formatted content (no appearance-presentation), we can get the output of these XML, and use XSLT to convert any form of appearance we want (HTML, WAP, palm, PDF, etc.). Using the PHP4 output cache and the Sablotron XSLT extension can do a good job.

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.