Home  >  Article  >  Backend Development  >  How to enable GZIP compression in PHP?

How to enable GZIP compression in PHP?

王林
王林forward
2023-09-13 18:13:021584browse

How to enable GZIP compression in PHP?

#GZIP compression is a simple and effective way to save bandwidth and speed up PHP applications. The mechanism working behind GZIP compression is described below -

Step1

The browser/client requests the file from the server.

Step2

The server sends the browser a .zip file (index.html.zip) in response instead of plain old index.html, so download time and bandwidth are reduced.

Step3 h2>

After executing the above steps, the browser will download the compressed file, decompress it, and then display it to the user. This loads web pages very quickly.

In the Apache server we have to add the following to the .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[&lsquo;HTTP_ACCEPT_ENCODING&rsquo;], &lsquo;gzip&rsquo;))
   ob_start(&ldquo;ob_gzhandler&rdquo;);
   else ob_start();
?>

The above is the detailed content of How to enable GZIP compression in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete