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
  2. I have read your blog its very attractive and impressive. I like it your blog.

    appvn

    ReplyDelete

Post a Comment

Popular posts from this blog

Multiple File Upload with PHP

Sometimes we need to allow our users to upload multiple file upload. On my previous post I was shown the basic of simple file upload with PHP. Today I am going to show you how to allow users to upload multiple files. It is almost similar like simple file upload but we need to do some modification with html markup and php code. multiple attribute is needed to add on the html markup. Major web browsers like Firefox, Chrome, Safari and IE 9+ support this attribute. Now I am going to show you how to upload multiple file with PHP and basic HTML form.

Live Comment System with jQuery Ajax PHP and MySQL

Recently I have been made a post that focused on how to submit form without page refreshing. That post shows the basic functionality of using jQuery Ajax. On the same follow this post will describe how we can create a comment system to post an instant comment without page refreshing. Let's start...

Resize Image While Uploading with PHP

On my previous post I was shown an example how to upload file with php and html. It was based on php simple image upload functionality. Today I am going to show you little bit advance of image uploading. Suppose if you run a website and want to allow users to upload image files than you need to think little bit about server's space and bandwidth. For this purpose you need to do some optimization with image files. Image resize while uploading is one of them. All major website do it in the same way. If a user uploads a 5mb image file they resize it in different sizes and store on there server. It helps them to seed up there website and reduce there budget. Now take a look, how we can do it ourself.