In extension to the compress() function posted below, here's a nifty little class that improves the idea a bit. Basically, running that compress() function for all your CSS for every single page load is clearly far less than optimal, especially since the styles will change only infrequently at the very worst.
With this class you can simply specify an array of your CSS file names and call dump_style(). The contents of each file are saved in compress()'d form in a cache file that is only recreated when the corresponding source CSS changes.
It's intended for PHP5, but will work identically if you just un-OOP everything and possibly define file_put_contents.
Enjoy!
$CSS_FILES= array('_general.css');$css_cache= newCSSCache($CSS_FILES);$css_cache->dump_style();//
// class CSSCache
//classCSSCache{
private$filenames= array();
private$cwd;
public function__construct($i_filename_arr) {
if (!is_array($i_filename_arr))$i_filename_arr= array($i_filename_arr);$this->filenames=$i_filename_arr;$this->cwd=getcwd() .DIRECTORY_SEPARATOR;
if ($this->style_changed())$expire= -72000;
else$expire=3200;header('Content-Type: text/css; charset: UTF-8');header('Cache-Control: must-revalidate');header('Expires: '.gmdate('D, d M Y H:i:s',time() +$expire) .' GMT');
}
public functiondump_style() {ob_start('ob_gzhandler');
foreach ($this->filenamesas$filename)$this->dump_cache_contents($filename);ob_end_flush();
}
private functionget_cache_name($filename,$wildcard=FALSE) {$stat=stat($filename);
return$this->cwd.'.'.$filename.'.'.
($wildcard?'*': ($stat['size'] .'-'.$stat['mtime'])) .'.cache';
}
private functionstyle_changed() {
foreach ($this->filenamesas$filename)
if (!is_file($this->get_cache_name($filename)))
returnTRUE;
returnFALSE;
}
private functioncompress($buffer) {$buffer=preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!','',$buffer);$buffer=str_replace(array("\r\n","\r","\n","\t",' '),'',$buffer);$buffer=str_replace('{ ','{',$buffer);$buffer=str_replace(' }','}',$buffer);$buffer=str_replace('; ',';',$buffer);$buffer=str_replace(', ',',',$buffer);$buffer=str_replace(' {','{',$buffer);$buffer=str_replace('} ','}',$buffer);$buffer=str_replace(': ',':',$buffer);$buffer=str_replace(' ,',',',$buffer);$buffer=str_replace(' ;',';',$buffer);
return$buffer;
}
private functiondump_cache_contents($filename) {$current_cache=$this->get_cache_name($filename);// the cache exists - just dump itif (is_file($current_cache)) {
include($current_cache);
return;
}// remove any old, lingering caches for this fileif ($dead_files=glob($this->get_cache_name($filename,TRUE),GLOB_NOESCAPE))
foreach ($dead_filesas$dead_file)unlink($dead_file);$compressed=$this->compress(file_get_contents($filename));file_put_contents($current_cache,$compressed);
echo$compressed;
}
}?>