Skip to content

Instantly share code, notes, and snippets.

@andreruffert
Created February 18, 2011 10:37
Show Gist options
  • Save andreruffert/833521 to your computer and use it in GitHub Desktop.
Save andreruffert/833521 to your computer and use it in GitHub Desktop.
Minify CSS
RewriteEngine On
RewriteRule ^styles.min.css$ styles.min.php [L]
<?php
$files = array(
'style.css'
,'jquery.ui.custom.css'
);
$modified = 0;
foreach($files as $file)
{
$age = filemtime($file);
if($age > $modified)
{
$modified = $age;
}
}
$offset = 60 * 60 * 24 * 7; // Cache for 1 week
header ('Expires: ' . gmdate ("D, d M Y H:i:s", time() + $offset) . ' GMT');
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $modified)
{
header("HTTP/1.0 304 Not Modified");
header ('Cache-Control:');
}
else
{
header ('Cache-Control: max-age=' . $offset);
header ('Content-type: text/css; charset=UTF-8');
header ('Pragma:');
header ("Last-Modified: ".gmdate("D, d M Y H:i:s", $modified )." GMT");
function compress($buffer)
{
/* remove comments */
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
/* remove tabs, spaces, newlines, etc. */
$buffer = str_replace(array("\r\n","\r","\n","\t",' ',' ',' '), '', $buffer);
/* remove other spaces before/after ; */
$buffer = preg_replace(array('(( )+{)','({( )+)'), '{', $buffer);
$buffer = preg_replace(array('(( )+})','(}( )+)','(;( )*})'), '}', $buffer);
$buffer = preg_replace(array('(;( )+)','(( )+;)'), ';', $buffer);
return $buffer;
}
ob_start('ob_gzhandler');
foreach($files as $file)
{
//compress files that aren't minified
if(strpos(basename($file),'.min.')===false)
{
ob_start("compress");
include($file);
ob_end_flush();
}
else
{
include($file);
}
}
ob_end_flush();
}
@kahlil
Copy link

kahlil commented Feb 18, 2011

Thx!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment