3 ways to compress CSS files using PHP

When you’re using a sophisticated design, CSS files can quickly become very long, and takes time to load. I have compiled 3 interresting ways of compressing CSS files by using PHP.

The Paul Stamatiou method

This method is the first I learnt, one year ago or so. In order to achieve it, you first have to rename your .css file to .css.php.
Make sure to import it in your html file by using their new name:

<link rel="stylesheet" type="text/css" media="screen" href="/style.css.php"/>

Once you successfully rename your css files, edit it and add the following code at the beginning of the file:

<?php if(extension_loaded('zlib')){ob_start('ob_gzhandler');} header("Content-type: text/css"); ?>

Then, add the next line to the very bottom and save the file.

<?php if(extension_loaded('zlib')){ob_end_flush();}?>

That’s all. While this method is useful and efficient.


The Perishable Press method

Basically, The Perishable Press method works as Paul Stamatiou’s method, by renaming your .css files to .css.php (or .php alone) and adding this short code snippet on the beggining of your CSS file:

   ob_start ("ob_gzhandler");
   header ("content-type: text/css; charset: UTF-8");
   header ("cache-control: must-revalidate");
   $offset = 60 * 60;
   $expire = "expires: " . gmdate ("D, d M Y H:i:s", time() + $offset) . " GMT";
   header ($expire);

I prfer this method this method to the one described by Paul Stamatiou because you don’t have to edit both the beginning and the end of the css file.


The Reinhold Weber method

I just stumbled upon this code snippet by German developer Reinhold Weber some minutes ago. The least I can say is that I like it.

  header('Content-type: text/css');
  function compress($buffer) {
    /* remove comments */
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
    /* remove tabs, spaces, newlines, etc. */
    $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
    return $buffer;
  /* your css files */


Why I like it? Because it is the only one of the 3 methods above which doesn’t require you to rename the CSS files to .php. Very nice to use on an existing site. The regular expression to strip out css comments is very nice too.



Leave a comment