How to Enable Gzip Compression in PHP for Faster Page Loads


PHP Code
  1. <?
  2. ini_set('zlib.output_compression_level', 5);
  3. #set the ini file with the compression level of your choice.
  4. #where 5 is you can change the compression level, it can be as high as 9 and as low as 0.
  5. #but be careful not to have to much compression, it can result in slow page loads
  6.  
  7. ob_start("ob_gzhandler");
  8. #now we will use output buffering to run the compression, make sure you put this at the very, very top of the pages you want compressed
  9. ?>



By the way, I use level 7 or 8 in compression, seems to work best for my site, one page used to take 16 seconds on my site to load with cashed clear, and ran the compression with cashed clear and it took about 5 seconds on level 8.

Hope you learnt a little and if everybody did this, we could make the internet a nice and fast loading, many forum systems compress their files, like phpbb and sm forums, if you want to do this with your forums and you find that it isn't running the compression, there should be an option in the admin panel, otherwise you can try adding it yourself.

Compression levels range from 0 (no compression) to 9 (maximum compression).
Using higher compression levels may save bandwidth but could increase CPU usage, potentially slowing down page loads on high-traffic sites.





Alternative


If your server supports it, enabling compression at the server level (e.g., in .htaccess for Apache) is more efficient than handling it in PHP. Example:

.htaccess
# Enable gzip compression in .htaccess
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json
</IfModule>
chrism's Avatar
Author:
Views:
2,446
Rating:
Posted on Saturday 21st December 2024 at 07:38 PM
DanielXP
DanielXP's Avatar
Added an .htaccess for Apache alternate for this
Posted on Saturday 1st March 2008 at 06:50 PM
ShadowMage
ShadowMage's Avatar
btw its cache =P
Posted on Wednesday 17th October 2007 at 05:58 AM
MCP
MCP's Avatar
^ Simple place that code into a file and call it compress.php or something. Then use a php include script on your pages. That way if change should need to come to the compression code... you won't have to put it on each page.
Posted on Friday 17th August 2007 at 05:39 PM
ilyas-shezad
ilyas-shezad's Avatar
Hi i hope ur still active cuz i wanted to ask if this works in a configuration file so u dont need to put it on every single page on ur website? thanks