This article has been rendered obsolete by this newer article. Read it for updated and better code.

As all web developers know, files can grow pretty big when building complex websites. Of course we can optimize the size of our CSS by using shorthands and cutting down on comments and whitespace but all of this goes at the cost of readability and maintainability. The best of both worlds would be to be able to work on nicely formatted and well commented CSS files while serving them as optimized as possible to our visitors.

The following handy little script takes care of this! Simply place it in the same directory where your CSS files are and change your <link> tags like this:

<link rel="stylesheet" type="text/css" href="/path/to/cssdir/css.php?file=mycssfile.css" />

You'll be served nicely on the fly while you can happily keep working on mycssfile.css without having to worry about a thing. Let's our CSS!

You can see it in action by comparing my uncompressed CSS to the compressed version.

Here's the PHP snippet:

ok, ok this code doesn't render right. I'll fix it tomorrow! For now, get the proper code here

<?php
header('Content-type: text/css');
if (!preg_match("/^([a-zA-Z0-9_-]+.css$)/", $_GET['file']))  {
	die('not a css file.');
}
if(file_exists($_GET['file'])) {
	$sText = file_get_contents($_GET['file']) or die('Could not open file.');
	$sText = preg_replace('!/*[^*]**+([^/][^*]**+)*/!', '', $sText);
	$sHash = md5($sText);
	header("Last-Modified: ".date("D, d M Y H:i:s T", filemtime($_GET['file'])));
	header("ETag: "{$sHash}"");
	echo str_replace(array("rn", "r", "n", "t", '  ', '   ', '    ', '     '), '', $sText);
	}
else {
	echo 'The file named "'.$_GET['file'].'" was not found on the server!';
}
?>

In case you're afraid of this affecting your server performance adversely there's always the possibility of adding a cache mechanism to it. I'll leave that up to you!

 
RockySomewhere near the Orion NebulaBookalicio.usGolden Gate BridgeThames River BankJackie and mePimpin' it