Compress CSS files using PHP

In order to save your precious bandwidth, you should compress your css files. Doing so is not hard at all using this snippet.

header('Content-type: text/css');
ob_start("compress");
function compress($buffer) {
  /* remove comments */
  $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
  /* remove tabs, spaces, newlines, etc. */
  $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
  return $buffer;
}

/* your css files */
include('master.css');
include('typography.css');
include('grid.css');
include('print.css');
include('handheld.css');

ob_end_flush();

Usage

Paste the code in a file named style.php. Don’t forget to include your css files (As seen on line 11 in the example). Once done, open your HTML document and import style.php as you’ll import a css stylesheet:


style.php will contain all your css stylesheets, compressed.

8 Comments

  1. Posted June 28, 2010 at 6:50 pm | Permalink

    Excellent! I tested it out on one of my sites and definitely decreased my loading time dramatically! Thanks!

  2. Posted June 28, 2010 at 7:03 pm | Permalink

    While this does work, it has one major drawback: it does not allow the web browser to cache the CSS files, resulting in the PHP script having to run, read from disk all of your stylesheets and deliver the combined CSS on EVERY request to your site.

    If you have many (5+) large stylesheets, this technique will be faster on the user’s first request (an unprimed cache), but will be slower on subsequent visits when they go deeper into your site, when the browser would normally serve up the cached CSS files.

    This sounds like a good idea in practice, but if your site serves up more than 2 pages to the majority of your visitors, you are actually slowing your site down.

    The optimal solution would be to combine all CSS files into 1 single CSS document.

    • Posted June 28, 2010 at 7:37 pm | Permalink

      Interresting point! I should definitely work on an improved version using your recommendations.

      • Christopher
        Posted July 5, 2010 at 3:08 pm | Permalink

        Nice little article!

        And the fact that John Karky pointed out is easy the solve. Just let the PHP script output the compromised CSS to a “master.css” file. Which is loaded by the browsers. It doesn’t take very long to just run the script if you change any CSS, so that should not be a problem.

    • Posted June 30, 2010 at 12:15 am | Permalink

      Yup. I would also merge (if posible) and minify everything to a single CSS file.

      Regards.

    • Serv
      Posted July 20, 2010 at 3:49 pm | Permalink

      Hi, excellent and very easy to implement!

      Would this css file solve the “problem”

      RewriteEngine on
      RewriteBase /css
      RewriteRule ^(.*)\.css$ $1.php [NC,L]

      or would the file be generated with each page impression, although the browser may load a cached .css-file?

      Regards

  3. Posted July 2, 2010 at 11:05 am | Permalink

    I was using this technique for long time, but after all, changed to PHP + .htaccess + ModRewrite .
    With PHP manipulate all CSS and Javascript files (combine, minify, compress) and cache them, then checking with ETag if any of files has changes siche last time (or cron schedule ).

    Result is like http://example.com/css/reset.css,text.css,framework.css,style.css
    same with javascripts

    ;)

  4. gabriel
    Posted July 30, 2010 at 7:24 pm | Permalink

    Nice script! I just made some modifications to check for valid files and etag for caching.
    Here is it: http://pastium.org/view/96b6e00ca972626ba6186a1a13eaf232

2 Trackbacks

  1. [...] This post was mentioned on Twitter by Jitendra Kumar, PHP Snippets. PHP Snippets said: PHP snippet: Compress CSS files using PHP http://bit.ly/desqXP #php [...]

  2. By 10 life-saving PHP snippets on July 19, 2010 at 4:08 pm

    [...] include('grid.css'); include('print.css'); include('handheld.css'); ob_end_flush();Source: http://www.phpsnippets.info/compress-css-files-using-phpGet short urls for TwitterAre you on Twitter? If yes, you probably use a url shortener such as [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>