Control PHP output: cache and compress dynamic pages _ php tips-php Tutorial

Source: Internet
Author: User
Tags crc32 xslt
The most satisfactory thing about PHP4 is that you can let PHP Cache all the output generated by the script before you decide to send them out, the browser does not receive any content. mod_gzip is an Apache module that uses Gzip to compress static html pages. browsers that comply with the IETF standard can accept gzip encoding (IE, netscape, etc ). Mod_gzip can increase the page download time by 4-5 times. I strongly recommend that you use mod_gzip on your web server. However, we must also use PHP to build our own compression engine. In this article, I will introduce how to use PHP output control functions to greatly accelerate page loading.

Introduction to PHP output control functions

The most satisfactory thing about PHP4 is that you can let PHP Cache all the output generated by the script. the browser will not receive any content before you decide to send them out. In a script program, you can use these functions to set headers and cookies. However, this is only a small part of the powerful output function.

The code is as follows:


Void ob_start (void );
?>

Tells the PHP processor to redirect all the output to an internal buffer. Before calling ob_start, no output will be sent to the browser.

The code is as follows:


String ob_get_contents (void );
?>

This function returns the output buffer as a string. You can call this function to send accumulated output to the browser. (Only after the buffering function is disabled !!)

The code is as follows:


Int ob_get_length (void );
?>

Returns the length of the cached string.

The code is as follows:


Void ob_end_clean (void );
?>

Clear the output cache and disable it. This function must be used before the cached content is output to the browser.
Void 501 ([int flag])
It is used to enable/disable the implicit flush action (disabled by default ). If flush is enabled, the output content is immediately sent to the browser every time you call print/echo or other output commands.

Use output control to compress PHP output
You must use the Zlib extension package compiled in PHP4 to compress the output. If necessary, you can view the instructions on Zlib package installation in the PHP documentation.
First, initialize the output cache:

The code is as follows:


Ob_start ();
Ob_implicit_flush (0 );
?>

Then, use print, echo, or other methods you like to generate all output content, for example:

The code is as follows:


Print ("Hey this is a compressed output! ");
?>

After the page is generated, we retrieve the output content:

The code is as follows:


$ Contents = ob_get_contents ();
Ob_end_clean ();
?>

Then, check whether the browser supports data compression. If yes, the browser sends the server a ACCEPT-ENCODEING HTTP header. We only need to check whether the $ HTTP_ACCEPT_ENCODING variable contains the "gzip, deflate" string.

The code is as follows:


If (ereg ('gzip, deflate', $ HTTP_ACCEPT_ENCODING )){
// Gzip compressed content is generated here
} Else {
Echo $ contents;
}
?>

This method is simple and clear in structure. Let's take a look at how to generate compressed output:

The code is as follows:


// Tell the browser that the gzip data will be received
// Before that, you have checked whether they support gzip and x-gzip data formats.
// If x-gzip is supported, the following header must be replaced by z-gzip.
Header ("Content-Encoding: gzip ");

// Display the gzip file header
// Display only once
Echo "x1fx8bx08x00x00x00x00x00 ";

// Calculate the file size and CRC code
$ Size = strlen ($ contents );
$ Crc = crc32 ($ contents );

// Compress data
$ Contents = gzcompress ($ contents, 9 );

// We cannot output this output because the CRC code is messy.
// If I use "echo $ contents" here, the compressed data will be sent out,
// But not complete. The last four bytes of the file are the CRC verification code, but only three bytes are sent.
// The last byte is lost. I don't know if this bug is fixed in version 4.0.2,
// The best way to avoid errors is to add the correct CRC check code to the end of the compressed data.
//
// Strip the old CRC verification code
$ Contents = substr ($ contents, 0, strlen ($ contents)-4 );

// Display only compressed data
Echo $ contents;

// Output CRC, and the size (in bytes) of the original data)
Gzip_PrintFourChars ($ Crc );
Gzip_PrintFourChars ($ Size );

Function gzip_PrintFourChars ($ Val ){
For ($ I = 0; $ I <4; $ I ++ ){
Echo chr ($ Val %256 );
$ Val = floor ($ Val/256 );
}
}

?>
// Well, you can add more compressed data in this way.

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

The code is as follows:


Ob_start ();
Ob_implicit_flush (0 );

Print ("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 %256 );
$ Val = floor ($ Val/256 );
}
}
?>

Cache PHP output

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

The code is as follows:


// Construct 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 verifies the Cache. you can use this function to check whether the Cache has expired or other specific conditions.
// Output is generated if the file is not in the Cache or is unavailable
Ob_start ();
Ob_implicit_flush (0 );
// 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 available, then:
Readfile ($ cached_file );

?>

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

Conclusion

PHP output control function is very useful for redirecting the output generated by the script to the cache. It can reduce the loading time for compressed cache data output by browsers that support gzip. It can also be used as a cache mechanism to reduce access to data sources (databases or files), which is of great significance to the use of XML.
If we use PHP to create an engine, cache the data obtained from the data source (xml document and database), and dynamically generate content in XML format (no appearance-presentation) we can get the XML output and use XSLT to convert it into any desired appearance format (html, wap, palm, pdf, etc ). Using the output cache of PHP4 and the Sablotron XSLT extension can well complete this task.

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.