Controlling PHP Output: Caching and compressing dynamic page _php tips

Source: Internet
Author: User
Tags chr crc32 flush xslt

Mod_gzip is an Apache module that uses gzip to compress static HTML pages, and browsers that follow IETF standards can accept gzip coding (IE, Netscape, etc.). Mod_gzip can increase the download time of the page by 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 explain how to use the output control function of PHP to dramatically speed up the page load.

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 headers, cookies, however this is only a small part of the powerful output function.

Copy Code code as follows:

<?php
void Ob_start (void);
?>

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

Copy Code code as follows:

<?php
String ob_get_contents (void);
?>

This function returns output buffer as a string. You can call the function to send the accumulated output to the browser. (only after the buffering function is turned off!!) )

Copy Code code as follows:

<?php
int ob_get_length (void);
?>

Returns the length of the string in the cache.

Copy Code code as follows:

<?php
void Ob_end_clean (void);
?>

Empties the output cache and closes the output cache. This function must be used before the content in the cache is exported to the browser.
void 501 ([int flag])
Use to turn on/off the implied flush action switch (the default is off). If the flush is open, each time a print/echo or other output command is invoked, the output is immediately sent to the browser side.

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

Copy Code code as follows:

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

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

Copy Code code as follows:

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

After the page is generated, we retrieve the output:

Copy Code code as follows:

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

You must then detect whether the browser supports compressed data. If supported, the browser sends a accept-encodeing HTTP header to the server side. All we need to do is check the $http_accept_encoding variable for a "Gzip,deflate" string.

Copy Code code as follows:

<?php
if (Ereg (' gzip, deflate ', $HTTP _accept_encoding)) {
To generate Gzip-compressed content here
} else {
Echo $contents;
}
?>

This method is easy to use and has a clear structure. Let's look at how to generate the compressed output:

Copy Code code as follows:

<?php
Tell the browser that you are going to receive gzip data
Of course, before that, you've checked to see if they support gzip,x-gzip data formats.
If the support is X-gzip, then the head below will be replaced with Z-gzip
Header ("Content-encoding:gzip");

Display the header of the gzip file
Just show once
echo "x1fx8bx08x00x00x00x00x00";

Calculates the file size and CRC code
$Size = strlen ($contents);
$CRC = CRC32 ($contents);

Compress data
$contents = Gzcompress ($contents, 9);

We can't just output this, because CRC codes are confusing.
If I use "echo $contents" here, the compressed data will be sent out,
But it's not complete. The last four bytes of the file were CRC checksum, but only three bytes were emitted.
The last byte was discarded. I don't know if this bug was solved in version 4.0.2,
But the best way to avoid errors is to add the correct CRC code to the end of the compressed data.
//
Split the old CRC check code
$contents = substr ($contents, 0, strlen ($contents)-4);

Show only compressed data
Echo $contents;

Output CRC, and the size of the original data (bytes)
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 also attach more compressed data in this way.

To do the actual testing, all the scripting code is as follows:

Copy Code code as follows:

<?php
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);
}
}
?>

Caching PHP output

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

Copy Code code as follows:

<?php
Constructs a filename for the requested URI
$cached _file=md5 ($REQUEST _uri);

if ((!file_exists ("/cache/$cached _file")) | | (!is_valid ("/cache/$cached _file")) {
Is_valid function Verification Cache, you can use this function to check whether the cache expires or other specific conditions.
Generate output If the file is not in cache or unavailable
Ob_start ();
Ob_implicit_flush (0);
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:
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. Cache data that is compressed for gzip-enabled browsers can reduce load time. It can also be used as a caching mechanism to reduce access to the data source (database or file), which is significant to the use of XML.
If we build an engine with PHP, cache the data (XML documents and databases) from the data source, and dynamically generate XML-formatted content (no appearance-presentation) we can get the output of these XML, and use XSLT to convert to any of the appearance formats we want (HTML, WAP, Palm, PDF, and so on). Using the PHP4 output cache and the Sablotron XSLT extension can do this task well.

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.