Fast, Effective PHP Compression

Normally, we just need config the apache setting to enable Gzip compression features.

#####
# Enable compression (gzip compression) – Apache Server (httpd)
# (start)
#
<IfModule mod_deflate.c>
    SetOutputFilter DEFLATE
    # file-types indicated will not be compressed
    SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|rar|zip|pdf)$ no-gzip dont-vary
    <IfModule mod_headers.c>
        Header append Vary User-Agent
    </IfModule>
</IfModule>
<IfModule mod_log_config.c>
    <IfModule mod_deflate.c>
        DeflateFilterNote Input instream
        DeflateFilterNote Output outstream
        DeflateFilterNote Ratio ratio
        SetEnvIf Request_URI \.(?:gif|jpe?g|png|rar|zip|pdf)$ ignore-log
        SetEnvIf Request_URI \.html image-request
        LogFormat '"%r" %{outstream}n/%{instream}n (%{ratio}n%%)' deflate
        CustomLog /var/log/apache2/deflate.log deflate env=!ignore-log
    </IfModule>
</IfModule>

<IfModule mod_expires.c>
    # enable expirations
    ExpiresActive On
    # expire GIF images after a month in the client's cache
    ExpiresByType image/gif "access plus 1 month 15 days 2 hours"
    # test that cached version is not used for the request
    ExpiresByType text/html "access plus 30 seconds"
    # check with cached version
    #ExpiresByType text/html "access plus 30 days"
</IfModule>

##### gzip configuration - (end)

Alternate Method

Place the following code before the (X)HTML content in any PHP script:

<?php if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start(); ?>

In this case, the ob_flush() command is unnecessary as PHP inherently flushes the buffer. The script delivers gzipped content to capable browsers and uncompressed content to incapable browsers.