Cache Control and GZIP with PHP

By: McSwindler

My host, 1&1, claims to allow gzip compression through Apache. However, when I try to set it up along with etags and expires it doesn’t seem to work. I devised this fancy script to add cache-control and etag headers to js, css, and xml files.

First, you must create a php file with the following code and upload it to your root directory (you can actually upload it anywhere, but the root is easiest). I named the file expire.php.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
$pathinfo = pathinfo($_ENV['SCRIPT_FILENAME']);
$extension = $pathinfo['extension'];
switch($extension){
    case 'css':
        header('Content-type: text/css; charset=utf-8');
        break;
    case 'js':
        header('Content-type: text/javascript; charset=utf-8');
        break;
    case 'xml':
        header('Content-type: application/xml; charset=utf-8');
        break;
    default:
        break;
}
$max_age = 300 * 24 * 60 * 60; // 300 days

$expires = time() + $max_age;
header( "Expires: " . date( "r", $expires ) );

$etag = dechex( getlastmod() );
header( "ETag: " . $etag );

$cache_control = "must-revalidate, proxy-revalidate, max-age=" . $max_age . ", s-maxage=" . $max_age;
header( "Cache-Control: " . $cache_control );
?>

Basically what is happening is the script first sets the correct content-type then calculates the expire date, sets the ETag, and finally sets the Cache-Control. What we need to do next is make sure this script prepends all php scripts. This is done by modifying php.ini.

If you have access to the root php.ini file you may modify that, however I do not so I simply created a new one and place it in my root directly. The php.ini file will be loaded for any php script in that directory or sub directories. Here is the code to place in php.ini

1
2
output_handler=ob_gzhandler
auto_prepend_file=DOCUMENT_ROOT/expire.php

Very important: You must change DOCUMENT_ROOT to the actual document root of your expire.php file. To get this use

1
phpinfo()

and search for “DOCUMENT_ROOT”. The output-handler line is how to get gzip compression on your files.

Now, for the final step, modifying .htaccess to run js, css, and xml files as php. Just add the following to your .htaccess file.

1
2
RemoveHandler .css .js .xml
AddType x-mapp-php5 .php .shtml .html .htm .txt .js .css .xml

And done, your files should now be gzip compressed and have expires headers.

One Response to Cache Control and GZIP with PHP

  1. Mike says:

    What works for PHP is to set the following through a php.ini file:

    1
    zlib.output_compression = On

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 
Δ
Back to Top