A programming & designing blog!

Saturday, February 23, 2013

CSS Compressing and Caching with PHP

Web developers always worried about there website's loading time. Because loading time is very important for a website's popularity. CSS compression and cache can speed up your website. I have created a PHP script for making CSS compression easy.
This script will allow you these functionalists:
  1. Reduce CSS file size by removing comments and white space characters
  2. Keep server side cache for rapid delivery.
  3. Enable GZip for compressed encode
  4. Enable user side cache smartly.


$css = $_GET['css'];
$expires = 60*60*24*14; // Cache lifetime 14 days
$baseName = basename($css); 
$cssCache = 'cache/'.$baseName;
$etag = md5_file($css); // Generate Etag
$fileModified = @filemtime($css);
$cacheModefied = @filemtime($cssCache);

Set 304 Not Modified if old visitor
if( @strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $fileModified && @trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
 header($_SERVER['SERVER_PROTOCOL'].' 304 Not Modified');
 Read CSS file from server side cache
 else if($cacheModefied > $fileModified){
 set_header($fileModified, $expires, $etag);
 New CSS file new browser set everythis
 set_header($fileModified, $expires, $etag);
 $cssData = file_get_contents($css);
 $compressed = compress($cssData);
 echo $compressed;
 cache($compressed, $cssCache); // Server side caching


function set_header($modefied, $expires, $etag){
 ob_start("ob_gzhandler"); //Gzip compress
 header("Etag: {$etag}");
 header("Content-type: text/css; charset: UTF-8");
 header("Pragma: public; maxage={$expires}");
 header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expires). ' GMT');
 header("Last-Modified: ".gmdate("D, d M Y H:i:s",$modefied).' GMT');

function compress($css){
 // Compress css
 $css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
 $css = preg_replace('/(\s(?=\W))|((?<=\W)\s)/', '', $css);
 $css = str_replace(array("\r\n","\r","\n","\t",'  ','    ','    '), '', $css);
 return $css;

function cache($data, $path){
 // Write server side cache
 $handle = fopen( $path ,'w+');  
    fwrite($handle, $data);

General Usage:

 Store save this script at the root directory as css.php and create a directory named cache. Now you can use this script like this on your project:
<link rel="stylesheet" type="text/css" href="css.php?css=css/style.css">


  1. 1) The gains you would make from this "compression" would probably be voided by the fact that you're serving the CSS *through PHP*.

    2) I don't know enough WordPress to know for sure but it definitely looks like a HUGE security whole in there. Assume I try reaching css.php?css=wp-config.php — wouldn't I get all of your sensitive data?

    Instead, I would recommend checkout out a proper assets handling library like Assetic. Or pre-compile your assets before deploying them, using something like YUI.

  2. I have read your blog its very attractive and impressive. I like it your blog.