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

By       
   

here.


Apache/2.4.18 (Ubuntu) Server at dcode.com.au Port 80
" data-via="andrewsirianni">Tweet

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:


<?php
  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']); }
      $this->force=$force;
      $this->referrer=$phpself;
      $this->doc_root=$doc_root;
    }

    public function add($src){
      $this->css[]=$this->doc_root.$src;
      return $this;
    }

    public function compile(){
      $filename='';
      foreach($this->css as $file){
        $filename.=$file;
      }
      $this->filename=md5($filename).'.css.php';
     
      // 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)){
        unlink($this->doc_root.'/inc/css/cache/'.$this->filename);
      }

      if(!file_exists($this->doc_root.'/inc/css/cache/'.$this->filename)){
        $csscode='';

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

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

        $cssfile=fopen($this->doc_root.'/inc/css/cache/'.$this->filename,'w');
        fwrite($cssfile,$csscode);
        fclose($cssfile);
      }

      $res=array();
      $res[0]='OK';
      $res[1]=$this->filename;
      return $res;
    }

    public function compress($buffer) {
      // remove comments
      $buffer=preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!','',$buffer);
      // 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 ...


<?php
  /**
  * 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.
  if($cssres[0]=='OK'){
    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:
PHPCSSCompressor



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.

Categories


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