Combine and minify CSS using get query string


/ Published in: PHP
Save to your folder(s)

The code is not particularly pretty but it does the job.

If you call this file css.php you can call it like this:

css.php?files=reset,style,iefix&minify=yes


Copy this code and paste it in your HTML
  1. // css.php
  2.  
  3. /*
  4.   If you name this file "css.php" then you can call it
  5.   using a GET query string like this:
  6.  
  7.   - css.php?files=reset,style,iefix&minify=yes
  8.  
  9.   There are two parts to the query string:
  10.  
  11.   1. The "files" part. Add your file names (with or
  12.   without .css) in a comma-separated list.
  13.  
  14.   2. The "minify" part. You can add "yes" to it, or
  15.   omit it entirely.
  16.  
  17.   When you have done this and loaded the file once the
  18.   script will cache, update, serve files and handle
  19.   everything else. You only have to specify which files
  20.   should be loaded and if it should be minified.
  21.  
  22.   The script will automatically update the cached files
  23.   whenever they become outdated, so you can edit your
  24.   individual CSS files as much as you like without
  25.   worrying about getting the most recent file.
  26. */
  27.  
  28.  
  29. // Handle the query string
  30.  
  31. if (isset($_GET['files']) && !empty($_GET['files'])) {
  32. $files = explode(',', strip_tags($_GET['files']));
  33. } else {
  34. $files = null;
  35. }
  36. if (isset($_GET['minify']) && !empty($_GET['minify'])) {
  37. $minify = (strip_tags($_GET['minify'])=='yes') ? true : false;
  38. } else {
  39. $minify = false;
  40. }
  41.  
  42. // Get the file names
  43.  
  44. $filesMissing = 0;
  45. foreach ($files as $key => &$name) {
  46. $name = trim($name);
  47. if (empty($name)) {
  48. unset($files[$key]);
  49. continue;
  50. }
  51. if (substr($name,-4) !== '.css') {
  52. $name .= '.css';
  53. }
  54. if ( ! file_exists($name)) {
  55. $filesMissing++;
  56. }
  57. $dates[] = filemtime($name);
  58. }
  59.  
  60. // If there are no file names, or if a file does not exist
  61. // then 404; Houston we have a problem...
  62.  
  63. if (empty($files) || $filesMissing > 0) {
  64. header("HTTP/1.0 404 Not Found");
  65. exit();
  66. }
  67.  
  68. // Is there a cached version and is it newer than the non-cached
  69. // files? If there is one then go directly to output
  70.  
  71. // !!! Make sure the directory "cached" is writeable !!!
  72.  
  73. $cachedFileName = 'cached/'.crc32(implode('.',$files)).($minify?'.min':'').'.css';
  74. $useCache = false;
  75.  
  76. if (file_exists($cachedFileName)) {
  77. $cachedLastModified = filemtime($cachedFileName);
  78. foreach ($dates as $d) {
  79. if ($cachedLastModified < $d) { $useCache = false; break; }
  80. }
  81. if ($useCache) {
  82. $code = file_get_contents($cachedFileName);
  83. goto output;
  84. }
  85. }
  86.  
  87. // If there is no cached version, or if the cached version is older
  88. // than the css files, then get the code from the css files and save a
  89. // cached version for future use
  90.  
  91. $code = '';
  92. foreach ($files as $name) {
  93. $code .= file_get_contents($name)."\n\n";
  94. }
  95. if ($minify) {
  96. $code = minifyCSS($code);
  97. }
  98. $f = fopen($cachedFileName, 'w');
  99. fwrite($f, $code);
  100. fclose($f);
  101. $cachedLastModified = filemtime($cachedFileName);
  102.  
  103. // The output
  104.  
  105. output:
  106. {
  107. header('Content-type: text/css; charset=utf-8');
  108. header('Last-Modified: '.gmdate('D, d M Y H:i:s',$cachedLastModified).' GMT');
  109. header('Expires: '.gmdate('D, d M Y H:i:s', time()+604800).' GMT'); // 1 week
  110. header('Cache-Control: max-age=604800'); // 1 week
  111. $encoding = false;
  112. $httpEncoding = strip_tags($_SERVER['HTTP_ACCEPT_ENCODING']);
  113. if(strpos($httpEncoding, 'x-gzip') !== false) {
  114. $encoding = 'x-gzip';
  115. }
  116. elseif(strpos($httpEncoding, 'gzip') !== false) {
  117. $encoding = 'gzip';
  118. }
  119. if ($encoding) {
  120. header('Content-Encoding: '.$encoding);
  121. $code = gzcompress($code, 9);
  122. }
  123. echo $code;
  124. }
  125.  
  126. // Function for minifying CSS code
  127. // Removes or truncates unecessary characters, whitespace and newlines
  128. function minifyCSS($code) {
  129. return preg_replace(array('/\/\*[\s\S]*?\*\//','/\s*([;:{},>+])\s*/','/(;})/',
  130. '/\r?\n/','/\t/'),array('','\1','}','',''),$code);
  131. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.