public
Last active

Css Minification on the Fly

  • Download Gist
minify.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
<?php
 
require_once('../includes/utils.php');
 
/**
* minify
*
* Class that handles the minification of all required CSS files
*/
class minify
{
public $css = '';
public $changed = false;
public $fileLastModified;
 
private $RequestedFiles = array();
 
/**
* __constructor()
*
* Builds the minified string
*
* @param array $GET
*/
function __construct($GET)
{
foreach($GET as $key => $val) {
if(util::strContains($key, 'css_')) {
$fileName = urldecode($val);
 
$this->RequestedFiles[] = $fileName;
 
if(!empty($_SESSION['lastRequestedCSS']) && !in_array($fileName, $_SESSION['lastRequestedCSS'])) {
$this->changed = true;
}
}
}
 
$_SESSION['lastRequestedCSS'] = $this->RequestedFiles;
 
foreach($GET as $key => $val) {
if(util::strContains($key, 'css_')) {
$fileName = urldecode($val) . '.css';
 
$fileModified = filemtime($fileName);
if(empty($this->lastModified) || $fileModified > $this->lastModified) {
$this->lastModified = $fileModified;
}
 
$strFileContents = file_get_contents($fileName);
 
if($strFileContents) {
$this->css .= $this->doMinify($strFileContents) . "\r\n";
}
}
}
}
 
/**
* doMinify()
*
* Perform the minification on the passed in string
*
* @param string $strFile
*
* @return string
*/
private function doMinify($strFile)
{
/* Strips Comments */
$strFile = preg_replace('!/\*.*?\*/!s','', $strFile);
$strFile = preg_replace('/\n\s*\n/',"\n", $strFile);
 
/* Minifies */
$strFile = preg_replace('/[\n\r \t]/',' ', $strFile);
$strFile = preg_replace('/ +/',' ', $strFile);
$strFile = preg_replace('/ ?([,:;{}]) ?/','$1',$strFile);
 
/* Kill Trailing Semicolon */
$strFile = preg_replace('/;}/','}',$strFile);
 
/* Return Minified CSS */
return $strFile;
}
}
 
session_start();
 
$minifier = new minify($_GET);
 
header("Last-Modified: " . gmdate("D, d M Y H:i:s", $minifier->lastModified) . " GMT");
 
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $minifier->lastModified) {
header("HTTP/1.1 304 Not Modified");
exit;
}
 
header('Content-type: text/css');
echo $minifier->css;

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.