Compress CSS / JS(Javascript) files Using PHP

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

In following techniques I will be using example of CSS files. The same technique can be replicated for js files.

The Paul Stamatiou method

  1. First you have to rename your .css file to .css.php
  2. Import it in your html file by using their new name:

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

  3. 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"); ?>

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

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

The Perishable Press method

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:

<?php
   ob_start ("ob_gzhandler");
   header ("content-type: text/css; charset: UTF-8");
   header ("cache-control: must-revalidate");
   $offset = 60 * 60 * 24; // Cache for a day
   $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.

Important Tip

CSS : Before applying any of this compression, you must optimize your css.


If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Other Posts which you may like:

Leave a Reply

Subscribe Me

Google Custom Search