Skip to main content

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.php:
include('function.php');

$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');
 exit;
}
/*
 Read CSS file from server side cache
*/
 else if($cacheModefied > $fileModified){
 set_header($fileModified, $expires, $etag);
 readfile($cssCache);
 exit;
}
/*
 New CSS file new browser set everythis
*/
 else{
 set_header($fileModified, $expires, $etag);
 $cssData = file_get_contents($css);
 $compressed = compress($cssData);
 echo $compressed;
 cache($compressed, $cssCache); // Server side caching
}

Function.php:

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);
    fclose($handle);
}

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">

Comments

  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.

    ReplyDelete

Post a Comment

Popular posts from this blog

Multiple File Upload with Progress Bar using PHP & jQuery

Some days age I have created a post that deals with How we can upload file with progress bar using php and jQuery. Some of my readers asked me how we can upload multiple files with progress bar. In this post I am going to show you how we can upload multiple files with progress bar.We can upload multiple files with progress bar exactly same way as I shown previous. But we need to do some modification with our file upload form and our php script to handle multiple files.

Force File Download with PHP

If you want to control or track your downloadable contents then a force file downloader script can give you more option. Especially if you want make images or other stemming contents like music file (mp3, wav, ogg), video files (flv, mp4, ogg, 3gpp), css, JavaScripts or even a php file downloadable then you must need to use a force file downloader script.
In this post I am going to share a simple but useful force file downloader script.

File Upload with Progress Bar using jQuery and PHP

In this post you will learn how to create a AJAX file uploading system with progress bar using jQuery and PHP. For this purpose we will going to use jQuery Form Plugin. It is a easy to use and powerful jQuery AJAX form submitting plugin. It supports XMLHttpRequest Level 2 and iframe file transportation. That's why it will work for both old and new browsers.