How To enable GZIP Compression in PHP?


GZIP Compression is a simple, effective way to save bandwidth and speed up PHP application. The mechanism runs behind the GZIP compression is described below −

Step1

The browser/client request for a file to the server.

Step2

The server sends a .zip file to the browser (index.html.zip) rather than plain old index.html in response, due to which the download time and bandwidth decreases.

Step3

After the execution of the above step, the browser downloads the zipped file, extracts it, and then shows it to the user. This loads the webpage very quickly.

In the Apache server, we have to Add the following to .htaccess file to enable GZIP compression.

# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xmlin
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
# Or, compress certain file types by extension:
<files *.html>
SetOutputFilter DEFLATE
</files>

Note

In PHP files we can enable GZIP compression.

<?php
   if (substr_count($_SERVER[‘HTTP_ACCEPT_ENCODING’], ‘gzip’))
   ob_start(“ob_gzhandler”);
   else ob_start();
?>

Updated on: 29-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements