Warning: mysql_connect(): Headers and client library minor version mismatch. Headers:100519 Library:100236 in /home/andrxvjf/public_etc/classes/database.class.php on line 2
Compress and Cache Your CSS Code On-The-Fly With PHP - Blog - Andrew Sirianni

Compress and Cache Your CSS Code On-The-Fly With PHP


With much of the styling of a web page now handles with CSS, the CSS files of a website can become quite complex. In order to maintain manageable CSS code, I often try to separate my CSS files depending on sections/elements of my website. However, at "run-time" on a production server, having multiple CSS files (with comments and indentation) can cause the site to perform (marginally) slower than an optimised site. Hence I wrote a PHP Class that can combine and minimise CSS files used on a web-page "on-the-fly".

Before I proceed, I must divulge that this is my first GitHub contribution and despite being keen to "give-back" to the OpenSource community, all comments and suggestions regarding my code/submission are greatly appreciated.

Now onto the class ...

The aim of the class is as follows:

So here is the CSS PHP Class:

  class CSS{
    protected $css     = array();
    protected $filename = '';
    protected $force   = 0;
    protected $referrer   = '';
    protected $doc_root = '';

    public function __construct($phpself,$force=1,$doc_root=''){
      if($doc_root==''){ $doc_root=dirname($_SERVER['DOCUMENT_ROOT']); }

    public function add($src){
      return $this;

    public function compile(){
      foreach($this->css as $file){
      // create folder if it doesn't exist
      if (!file_exists($this->doc_root.'/inc/css/cache/')) {
        mkdir($this->doc_root.'/inc/css/cache/', 0777, true);

      if($this->force==1 && file_exists($this->doc_root.'/inc/css/cache/'.$this->filename)){


        foreach($this->css as $file){
          $csscode.='/*** CSS File: '.$file.' ***/'."\n".file_get_contents($file)."\n\n\n";

        $csscode='<?php if(extension_loaded(\'zlib\')){ob_start(\'ob_gzhandler\');} header("Content-Type: text/css"); ?>'."\n".
          '<?php if(extension_loaded(\'zlib\')){ob_end_flush();}?>';


      return $res;

    public function compress($buffer) {
      // remove comments
      // remove tabs, spaces, newlines, etc.
      $buffer=str_replace(array("\r", "\n", "\t"), '', $buffer);
      $buffer=str_replace(' ', ' ', $buffer);
      $buffer=str_replace(' {', '{', $buffer);
      $buffer=str_replace(';}', '}', $buffer);
      $buffer=preg_replace("!/\ ?([>|\+|,])\ ?/!","\1",$buffer);
      return $buffer;

... and here is a sample file to show its usage ...

  * CSS Compressor
  * Script to combine CSS files
  # Step 1: Call the class
  require_once 'css.class.php';

  # Step 2: Initiate the class, SELF, Force Re-cache (1/0), Document Directory
  $cssCache = new CSS($_SERVER['PHP_SELF'], 1, dirname($_SERVER['DOCUMENT_ROOT']));

  # Step 3: Add your css files that you want to combine and minize
  $cssCache->add('LINK TO CSS FILE');

  # Step 4: Compile the CSS
  $cssres = $cssCache->compile();

  # Step 5: Include the combined file: $cssres[0] will let you know if it has worked; $cssres[1] will be the name of the combined CSS file.
    echo '<link href="'.$cssres[1].'" rel="stylesheet" type="text/css" />';

I hope that this has been useful to you and will greatly assist in managing your CSS while still enabling you to ensure that your website runs at an optimum.

Please share all comments and feedback - your thoughts are greatly appreciated!

Download this project on GitHub at:

comments powered by Disqus

About Me

I design & develop software that runs on the Internet. As a qualified analyst, accountant and real estate agent, I can deploy systems that improve performance.


Warning: DOMDocument::load(https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=andrewsirianni&count=5): failed to open stream: HTTP request failed! HTTP/1.0 410 Gone in /home/andrxvjf/public_etc/templates/rmargin/twitter.tpl.php on line 8

Warning: DOMDocument::load(): I/O warning : failed to load external entity "https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=andrewsirianni&count=5" in /home/andrxvjf/public_etc/templates/rmargin/twitter.tpl.php on line 8

Recent Tweets

Follow me: @andrewsirianni

Copyright ©2012 Andrew Sirianni, All Rights Reserved   LinkedIn Profile