Control the output of PHP: Caching and compressing dynamic pages _php tutorial

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.

Copy the Code code as follows:
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.

Copy the Code code as follows:
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!!) )

Copy the Code code as follows:
int ob_get_length (void);
?>

Returns the length of the string in the cache.

Copy the Code code as follows:
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:

Copy the Code code as follows:
Ob_start ();
Ob_implicit_flush (0);
?>

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

Copy the Code code as follows:
Print ("Hey This is a compressed output!");
?>

After the page is generated, we retrieve the output:

Copy the Code code as follows:
$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.

Copy the Code code as follows:
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:

Copy the Code code as follows:
Tell the browser that you are going to receive gzip data
Of course, before you have checked whether they support the Gzip,x-gzip data format
If the support is X-gzip, then the following head will be replaced with Z-gzip
Header ("Content-encoding:gzip");

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

Calculate 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 the CRC code is chaotic.
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 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,
However, the best way to avoid the error is to add the correct CRC checksum to the end of the compressed data.
//
Stripping 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 perform the actual test, all the script code is as follows:

Copy the Code code 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 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:

Copy the Code code as follows:
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 cache is out of date or other specific conditions.
Generates output if the file is not in the cache or is not available
Ob_start ();
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:
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.

http://www.bkjia.com/PHPjc/327582.html www.bkjia.com true http://www.bkjia.com/PHPjc/327582.html techarticle 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 be the page of ...

  • 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.