English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP implementation of web page compression function based on ob_start(ob_gzhandler)

This article describes a method for implementing web page compression on PHP based on ob_start('ob_gzhandler'). Share it with everyone for reference, as follows:

After PHP generates a web page and sends it to the browser for display, the page loading speed is not only related to the user's internet speed, but often also related to the size of the page. We can start with the page size to improve the response speed of the web page.

The following code is an example of compressing a web page, we use the ob_gzip function to compress the output content and put it into the 'buffer' before outputting.

PHP code

//Enable compression
if(function_exists('ob_gzip'))
{
 ob_start('ob_gzip');
}
//Prepare some content to be compressed
for($i=0; $i<100; $i++)
{
 echo('This is a test content <br>');
}
//Output compressed results
ob_end_flush();}}
//This is the ob_gzip compression function
function ob_gzip ($content)
{
 if( !headers_sent() && extension_loaded ("zlib") && strstr ( $_SERVER["HTTP_ACCEPT_ENCODING"], "gzip")){
 $content = gzencode($content,9);
 header ("Content- Encoding: gzip");
 header ("Vary: Accept- Encoding");
 header ("Content- Length: ".strlen ($content));
 }
 return ($content);
}

How much effect it has, I tested the code above here.

Before compression:

Compressed:

Readers who are interested in more PHP-related content can check the special topics on this site: 'Summary of PHP Network Programming Techniques', 'Summary of PHP Caching Technology', 'PHP Data Structures and Algorithms Tutorial', 'Complete Collection of PHP Array (Array) Operation Techniques', 'Summary of PHP String (string) Usage', 'Summary of PHP Program Design Algorithms', 'Summary of PHP Mathematical Operation Techniques', 'Summary of PHP Regular Expression Usage', 'Summary of PHP Arithmetic and Operator Usage', and 'Summary of Common Database Operation Techniques in PHP'.

I hope the content described in this article will be helpful to everyone in PHP program design.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously, and this website does not own the copyright. It has not been manually edited and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)