Transparently compressing JS and CSS files with PHP

When I develop a web site, I usually configure it to compress the content before sending it to the end user. Downloading resources such as HTML, CSS and JS files is then smaller and thus faster.

It is possible to configure this in the .htaccess file (in case the server runs Apache) as well as it is possible to program it in PHP.

Unfortunately, it looks like my web hosting company doesn’t allow the former, so I had to take the PHP way for compressing resources in geo:truc.

The PHP code for doing this is rather simple:

This works fine: write a PHP script, put the code above in it, and it’s done! It works with HTML files, and it’s possible to use it as well with JS ans CSS files, although they need to start with this snippet and have a .php extension.

But how to do when using different JavaScript libraries that are now commonly used? A new .php file for every new version of jQuery? It sounds fastidious. And how to make it transparent, i.e. not passing a URL like http://www.example.com/js/compress.php?file=jQuery.js ?

I must say that I tried first to use Google CDN for using jQuery, which would be both minified and gzipped. But the response time was rather slow, both for identifying the application and then for getting a response from Google (HTTP 200 or HTTP 304). And this is useless for jQuery plugins as well as my own JS-library. So, after a few weeks, I decided to get rid of the CDN-concept.

So let’s go back to PHP. The idea is simple: start a gzipped output buffer, open a resource file and send everything! For instance:

Now how to cheat for transforming the file name provided in the path into a parameter?

One way would be to use mod_rewrite in Apache, and within .htaccess having rules for splitting URLs and passing the resource name as a parameter to a .php script. This is a good solution, probably the best one. Alas, it doesn’t work at my web hosting.

Another way is to create a fake directory rsc/ containing only one .htaccess file, the different resources staying in their respective directories. So the call of a JS file will be

instead of

Then use the ErrorDocument instruction in the .htaccess file, and make it invoking the script for compressing. For instance if my script is called rsc.php and stored in the src/ directory:

Now how can rsc.php get the parameter? By using $_SERVER['REQUEST_URI']:

That’s it! From here it’s possible to get the resource name, and using it with the small compression script above!

If you want to use those ideas, the concepts presented here are used in RSC (ReSource Compression), which is used with geo:truc and is available at github.