3 ways to compress CSS files using PHP

by Jean. 114 Comments -

When you’re using a sophisticated design, CSS files can quickly become very long, and takes time to load. I have compiled 3 interresting ways of compressing CSS files by using PHP.

The Paul Stamatiou method

This method is the first I learnt, one year ago or so. In order to achieve it, you first have to rename your .css file to .css.php.
Make sure to import it in your html file by using their new name:

<link rel="stylesheet" type="text/css" media="screen" href="/style.css.php"/>

Once you successfully rename your css files, edit it and add the following code at the beginning of the file:

<?php if(extension_loaded('zlib')){ob_start('ob_gzhandler');} header("Content-type: text/css"); ?>

Then, add the next line to the very bottom and save the file.

<?php if(extension_loaded('zlib')){ob_end_flush();}?>

That’s all. While this method is useful and efficient.

Source

The Perishable Press method

Basically, The Perishable Press method works as Paul Stamatiou’s method, by renaming your .css files to .css.php (or .php alone) and adding this short code snippet on the beggining of your CSS file:

<?php 
   ob_start ("ob_gzhandler");
   header ("content-type: text/css; charset: UTF-8");
   header ("cache-control: must-revalidate");
   $offset = 60 * 60;
   $expire = "expires: " . gmdate ("D, d M Y H:i:s", time() + $offset) . " GMT";
   header ($expire);
?>

I prfer this method this method to the one described by Paul Stamatiou because you don’t have to edit both the beginning and the end of the css file.
Source

The Reinhold Weber method

I just stumbled upon this code snippet by German developer Reinhold Weber some minutes ago. The least I can say is that I like it.

<?php
  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();
?>

Why I like it? Because it is the only one of the 3 methods above which doesn’t require you to rename the CSS files to .php. Very nice to use on an existing site. The regular expression to strip out css comments is very nice too.
Source

You probably guessed it, my favorite method of the 3 above is the last one. And you? Did you already tried any of theses methods? Which one is your favorite? Tell us in the comments.

  • http://www.badcat.com Kel

    Excellent Tip! I’ve seen the Perishable one before but the RWeber version is slick. Thank you!

  • http://www.thepowerblogger.com power Blogger

    Thanks a lot for this. I was looking for this one.

  • http://techblog.procurios.nl Taco van den Broek

    I’v used a combination of the three methods:

    - Create a hash of the css files used
    - Check if a file with that hash exists, if not:
    - Concat and minify (i.e. remove whitespace and comments like in the Reinhold Weber method) the contents of the css files
    - Cache the resulting data in a css file within the webroot
    - Add a link to that file in the resulting HTML file

    The resulting file is served by Apache using mod_expires to set the right expires header (+1 month) and mod_deflate to gzip the output. The hash created contains information about the version of the file so when the css contents change a different filename will be generated.

  • http://www.wprecipes.com Jean-Baptiste Jung

    @Taco: Seems very interesting, I should try it sometimes. Thanks for sharing :)

  • CLee

    No matter which method you use, you might want to add these headers so browsers can cache your css file. If not, browsers will end up re-querying the compressed css and that may cause an overhead on server side.

    $offset = 60 * 60 * 24; // Cache for a day
    header(‘Content-type: text/css’);
    header (‘Cache-Control: max-age=’ . $offset . ‘, must-revalidate’);
    header (‘Expires: ‘ . gmdate (“D, d M Y H:i:s”, time() + $offset) . ‘ GMT’);

  • http://vetpetinsurance.blogspot.com Catrin W

    I didn’t even know this was possible. Is it needed if your server is running mod_gzip or mod_deflate? I was under the impression that that compressed everything.

  • http://bedre.no Torkil

    I have played around with compressing CSS as well, and there is alot of more whitespace to kill:
    - whitespace on both sides of commas ,
    - whitespace on both sides of curly brackets {}
    - whitespace on both sides of colons :

    But: You can do alot more than just removing whitespace:

    Remove ending semicolons:
    .class {color: #000; } becomes .class{color:#000}

    0.90em compresses to .9em
    0px, 0%, 0em etc all compresses to 0

    Then you can of course combine stuff to use shorthand syntax:
    #ffffff becomes #fff
    padding: 2px 0 2px 0 becomes padding: 2px 0
    background: url (‘image.gif’) no-repeat right center becomes background:url(image.gif) no repeat 100% 50%.

    You can also remove declarations of default stuff. Background position: top left for instance.

    Minify is a great project too:
    http://code.google.com/p/minify/

    Minify will even leave your comment hacks in there.
    Just get the css-class from the sourcecode and use it as a standalone tool, thats a good start!

  • http://blog.cristiandeluxe.com Cristian Deluxe

    Sorry for my bad English.
    This is how I compress my css and js files:

    I have 2 separated folders “/css” and “/js”

    In “css” folder create a new .htaccess file and put this on it:

    AddHandler application/x-httpd-php .css
    php_value auto_prepend_file gzip-css.php
    php_flag zlib.output_compression On

    Now create a new file called “gzip-css.php” and put this on it:

    For javascript is the same, only change css for js inside files and file names.

    Now you have all your files encoded and don’t need to modify or change each css and js!!.

    Best regards.
    Cristian

  • http://blog.cristiandeluxe.com Cristian Deluxe

    I did again! Sorry.

    Code pasted in: http://pastebin.com/f70402922

  • http://bedre.no Torkil

    Cristian: Nice method there, but if you have multiple CSS-files you will make multiple HTTP-requests, and that is something you’d want to avoid. Combining the files into one file, like in the Reinhold Weber method, would be better.

    Same goes for graphics. Try googling for sprites webdesign.

  • http://flowoflogic.com Patrick

    I used to use a system almost identical to Christian’s – however, when I started using systems like WordPress or ExpressionEngine or Habari, where css or js files might be sent from many different folders, and manually putting the .htaccess and gzip files may not be convenient, I created a different system.

    I have posted about it here:
    http://www.lateralcode.com/2008/12/gzip-files-with-htaccess-and-php/

  • http://www.wprecipes.com Jean-Baptiste Jung

    @Patrick: INterresting exemple, thanks for sharing it with us! Too bad I didn’t knew it before, I should have been inclued it in this article!

  • Pingback: PHP ile CSS Dosyalarınızı Sıkıştırmak için 3 Farklı Yöntem | Barış Yüksel | brsyuksel

  • http://bedre.no Torkil

    Nice example from Patrick too, but again: Combining multiple CSS-files into one file really has it’s advantages.

  • http://flowoflogic.com Patrick

    Torkil, it is not always possible to use the combine CSS method (especially when using blogging systems), and it is always good to have backups on hand in those situations.

  • http://bedre.no Torkil

    I am not talking about the method mentioned in this article in particular.

    CSS files are loaded in sequence so that rules in later files override identical rules in previous files. As long as you combine the CSS files in the same sequence, I don’t see any situations where you would not want to or would be unable to combine CSS files.

  • http://magnusmag.com James White

    Why not just turn zlib compression on in IIS or Apache for css filetypes? :)

  • Pingback: Free Premium Social Media WordPress Theme: WicketPixie » Wordpress themes marketplace

  • Pingback: Wordpress Blog Services - 2008 Most Popular Design posts, Tutorials and Resources

  • http://www.0window.com/blog/ Catrin W

    Very interesting tips. I never thought of compressing long css files, but now i will for sure. I guess that the last one will be my favorite one as it is the simplest :-). Thanks for sharing.

  • http://www.evowebdev.com Ray G.

    Great tips! Love the last one that does not require renaming css files.

  • Pingback: 2008年最佳Web设计文章、教程及资源 - 刀客征途

  • Pingback: 3 ways to compress CSS files using PHP | CNSQ Online Blog

  • Pingback: 3 ways to compress CSS files using PHP | Urban Mainframe

  • Nitroadict

    The last method does not work for me, however, the first method appears to work (I checked with phpinfo.php, so my host definitley has zlib, and using the 1st method, nothing broke, so I’m assuming it worked…)

    However, the 3rd option was the first one I intended to use. Anyone know whats going on? :\

  • Pingback: 2008 Most Popular Design posts, Tutorials and Resources | Web Hosting and Domains

  • Pingback: 2008 Most Popular Design posts, Tutorials and Resources | SulVision

  • http://feliperibeiro.com Felipe Ribeiro

    Why not just use Apache mod_deflate and avoid the overhead of using PHP every request to process a static file? Or even better if you can have something like lighttpd or thttpd to handle just the static files and compress them, even faster.

  • http://bedre.no Torkil

    All good and well if you have root access to the server I guess.

  • Pingback: Have to say » Blog Archive » 50个Web开发设计文章、教程及资源

  • http://www.intergraphicdesigns.com Ricardo Arce

    If you want to see a spanish translation of this article:

    Si dese consultar este artículo en español puede visitar el siguiente enlace:

    http://www.intergraphicdesigns.com/blog/php-mysql/2009/01/gua-para-comprimir-archivos-css-con-php.html.

    En este enlace InterGraphicDESIGNS traduce al idioma español esta guía para comprimir archivos CSS utilizando PHP, y además ofrece algunas observaciones para la mejora del rendimiento en cuanto a esta idea.

  • Pingback: tutorialand.com

  • Zahl

    I did not actually try the code, but wouldn’t replacing all spaces break stuff like “border: 1px solid black;” because it would be turned into “border:1pxsolidblack;”?

  • Pingback: *real me » Bookmarks on 2009-01-19

  • Pingback: 2008 Most Popular Design posts, Tutorials and Resources | Web2.0

  • http://www.rnbhaven.com/90s-music/artists/Boyz-II-Men/10 Boyz II Men

    Wow, I had never heard of anything like this before. What makes this benefit your site? I’m just curious before I implement the functionality.

  • http://bedre.no torkil

    Compressing your CSS-files makes the whole website load faster (obviously).

    Combining multiple CSS-files into one CSS-file reduces the number of HTTP connections a client has to open up to read your site, and thus also decreases loadtime :)

  • http://noneyet bob joseph

    For #3 above, where do you insert code for a WordPress installation?

  • Pingback: 20 Useful PHP Components & Tutorials for Everyday Project | Noupe

  • Pingback: Wordpress Blog Services - 20 Useful PHP Components &amp; Tutorials for Everyday Project

  • http://mrclay.org/ Steve Clay

    Shameless plug: Minify was designed expressly for this task.

    @Felipe:
    mod_deflate should certainly be faster than ob_gzhandler(), but if you cache pre-encoded files to disk, PHP can actually serve them faster (using readfile()) than Apache can with mod_deflate. It seems mod_deflate doesn’t cache the encoded version and has to re-encode on each request.

  • Pingback: blog.no-panic.at » links for 2009-03-03

  • http://forum.alsacreations.com Felipe

    Beware of removing too much whitespace in CSS: removing whitespace before ‘{‘ may trigger a known bug in IE6: sth:first-line{property: value;} won’t be read by IE6 but sth:first-line {property: value;} will be OK.

  • http://www.conversem.com Ruben

    Excellent tips.
    It’s bookmarked and I will definitely use this.

    Thanks!

  • http://www.wprecipes.com Jean-Baptiste Jung

    @Felipe: Didn’t know that! Thanks for the expert advice :)

  • http://mrclay.org/ Steve Clay

    @Felipe: Good to know. Bug filed.

  • http://cwebconsultants.com mani

    Hi everyone,

    I have never used CSS compression on my websites before. And now wants to do this. Can you please let me know… Why should we do this and at what level means what should be the minimum css file size on which we should perform the compression.

    I am really looking forward to your suggestions.

  • http://www.freesoftwareworkshop.com Nicholas

    Hello,

    Thanks for the great article, I will try to implement the 3rd method as you suggested, although I didn’t understand where to place the code…

    Regards,
    Nicholas

  • Pingback: php note» Blog Archive » CSS圧縮転送について

  • Pingback: 20 Useful PHP Components & Tutorials for Everyday Project « Hdeya team blog

  • Pingback: Angels Picks » Blog Archive » 20 Useful PHP Components & Tutorials for Everyday Project

  • http://killerinvestments.net/category/green-investing/ Green Investments

    Wouldnt this make it longer to load the css file? Every time it loaded, the server would have to decompress the css and then publish it. Im not sure exactly how it works…

  • Pingback: Comprimir CSS con PHP « Gambitomeister

  • http://travel.web-sababa.co.il/ Mati

    great post, I will surely try these methods, my blogs are too slow ..

  • Pingback: Blog InterGraphicDESIGNS » Guía para comprimir archivos CSS con PHP?

  • Pingback: How To Achive Maximum Website Performance (Part 3) « Sascha Kimmel - Living The Web Experience Since 1996

  • http://www.ethanandjamie.com/ Ethan Gardner

    The best option for me was to create a php file in the same directory as the CSS files. I used the ob_gzhandler from method 2 and combined it with the comment removal and include concept from the 3rd method.

    This way, I got the benefit of keeping the css extension on the files and fewer http requests with the more powerful gzip compression since my site is on a shared host that has mod_deflate turned off.

    I left the file as multiline CSS so I can get an approximate line number when using Firebug to troubleshoot any layout issues. The method I pieced together will become part of my standard process. Thank you for this post.

  • Pingback: links for 2009-05-25 | NeXt

  • http://www.iflexion.com Iflexion

    Hm… Interesting. :)
    Never thought such a thing makes tangible changes.
    I’ll try. :)

  • Pingback: WebDev Best Practices – Parte 1 | José Ricardo

  • http://www.authorityguide.info pete

    Thanks for the tips. I have been using my site with Adwords.. everything was fine but one day suddenly got slapped with poor QS due to landing page problems… after much investigation got to know that my landing page was taking too much time to load…. one of tips to reduce the lp load time is to compress the files.. I had managed to compress the PHP files but did not know that one could also compress the CSS… Hopefully now my campaigns will go live again.

  • Arthur

    Am I crazy or is it not possible to cache gzipped files?

    I’ve added all of the proper headers but Firebug is showing that the files are in fact not caching. It only seems to cache “304 Not Modified” js & css files… I’ve spent all day trying to fix this… Is there any other way to verify if the files are being cached? After minifying css & js files and adding gzip the savings are incredible, it would be a shame if this was not cache-able.

  • Pingback: Waschen, schneiden, legen - oder wie man CSS Dateien gekonnt optimiert | seo-geek - Webseiten gezielt optimieren

  • anthony

    Sorry I’m new to this compression thing. Should I just add the no. 3 method like this:

    or

    on my php pages?

  • Georgiy

    Thanks, very short and informative. ;-)
    Method 3 is quite nice, but i’d like also to put my two cents in it.
    If your site uses cookies, they are sent with every request, including images, css and js requests, unless you specify a subdomain like images.mysite.com. But it sounds not as a good idea to put absolute paths to images in your css. However, the Reinhold Weber lets us do this with one line of php code:

    // set cookie-free path for images
    $buffer = str_replace(‘../images/’, ‘http://images.mysite.com’, $buffer);

    To make it even less hard-coded, I used the following:
    @$img_url = $_GET['img_url'];
    $buffer = str_replace(‘../images/’, $img_url, $buffer);

    And, in my view, where I have access to all my helpers, it looks like this:
    <link rel="stylesheet" href="css.php?img_url=” type=”text/css” media=”screen” />
    Not very readable, but I personally like it.

  • Georgiy

    oops, the parser ate all my helpers. but i think you caught the idea.

  • http://www.relaxguru.blogspot.com ajith

    Thanx to The Perishable Press method

  • http://blog.moonreturn.com/ jay bharta

    How can we replace .php file over .css file

    Very Simple.

    STEP1: This is your abc.php page

    <!—->

    STEP2: This your zero.php (actually zero.css renamed with zero.php) page

    #s1{
    /*background:transparent url(../images/img_main.jpg) repeat scroll 0 0;*/
    background:transparent url(../images/) repeat scroll 0 0;
    border-bottom:1px solid #A0A0A0;
    float:left;
    height:208px;
    position:relative;
    width:1002px;
    }

  • Pingback: Reducing Your Joomla Website’s Load Time | Blog of PB Web Development

  • http://www.haefelinger.it geronimo

    Alternative 3 is rather nice, nevertheless, here are my remarks:
    1. Just putting ‘ into a .css file will usually not work. You need in addition tell the web server to handle .css (or the particular one in question) as a PHP document.

    2. The compressor function in alternative three appears not correct to me. Consider cases like ‘html\tdiv’ and ‘html\ndiv’. Both examples would be ‘compressed’ as ‘htmldiv’ and that is not what we want.

    3. Instead of using str_replace() I propose to use a single regex like !\s\s+|\n|\t|/\* .. !

    This is the ‘compress’ function I’m using:

    function compress($buffer) {
    $regex = “,/\*.*?\*/|\s+,s”;
    return preg_replace($regex,’ ‘,$buffer);
    }

    Not optimal in terms of compactness, while at least correct (well, at least no known problems).

    Greetz.

  • Dalibor Sojic

    I like The Reinhold Weber method, but it would be nice to combine it with gzip.

    How to call 2 functions (compress and gzip)??

  • http://officialmp3s.com/ Andy Moore

    Thanks!

    I’ve been working on making my site faster with FireBug and Google’s PageSpeed extension and I’d been wondering how to finally get the CSS compressed to the point where it passed that bit of the test.

    The third option worked perfect first time, appreciated.

    Another tick on the sucking up to Google checklist though having a faster site is nicer for all!

    :)

  • Pingback: How to speed up your blog loading time

  • Pingback: How to speed up your blog loading time – multimediaDev

  • http://www.hostingangle.com/home/ Hussain

    thank you for sharing the tips.. :)

    not going to add new ways but will share my experience with you..

    my result and final decision:
    1- minify, combine, and compress js files (plus archiving to avoid repeating!)
    2- minify and compress css files (no combine no archiving)

    a bit of details;
    after trying several ways and best practices especially after using javascript framework libraries such as prototype and scritpaculous and incorporating them into our own CMS framework..minifying these files (of the js framework) takes a lot of work, and once you are happy with the result, an update is there offering new features!

    keeping up with updates is hectic if it involves manual editing !
    (this is a really important criterion to decide which method to use)

    another issue is when having different themes that the web master likes to be changing from time to time..using different CSS and JS files.

    so hopefully you can relate this to your coding experience :)

  • Valerie

    Feeling really stupid here since everyone else seems to get it, but I’m a newb, what can I say?

    I’d like to try #3 – but I have no idea where to put that. I’m using a WordPress site. Do I put that at the top of my header.php file? Or what?

    Thanks for any help!

  • http://www.archetoy.com Ryan

    Don’t feel stupid Valerie,

    yeah, mehtod 3 goes into your header, for example:

    .
    I think this is ok, but, i don’t want to pull the code into my header, so, think I’ll try one of the other methods.

    Anyone know if linking to one css file, and using:

    @import url(“reset.css”);
    @import url(“960.css”);
    @import url(“text.css”);
    @import url(“joomla.css”);

    Within that file would work?

    Great writeup BTW, thanks for sharing!

  • http://www.archetoy.com Ryan

    Doh, stripped the code, put the code bewtween a “style type= text/css tag, in your header, like:

  • http://mhuntdesign.com Matthew Hunt

    This is how I setup the 3rd method:

    link rel=”stylesheet” type=”text/css” href=”css/css.php” media=”screen”

    add the php snippet to a file called css.php, then link to it using usual link tag.

  • Pingback: Optimización: Utilizar compresión Gzip | Flash Platform

  • http://www.sparsh-technologies.com Sparsh

    Nice tips you have shared. I haven’t thought before. I will try it. Thanks for sharing this informative post!

  • Pingback: How To Speed Up Your Blog Loading Time « R@j@. R.K

  • Pingback: Compresser et ranger son CSS avec PHP. | Darklg Blog

  • Pingback: Useful PHP Components & Tutorials for Everyday Project « UR-Technology

  • http://www.vinfotech.com Ranu

    Great post….I will definitely implement it…..Many thanks for sharing…..

  • http://www.logofoo.com/ Dan – LogoFoo.com

    The Perishable Press method just seems work smooth. I never thought that CSS could be compressed with PHP. Thanks!

  • http://austinpassy.com The Frosty

    Could really use a CSS overflow for your pre HTML code snippets. Text gets lost and there’s no way to read whats hidden.

    ;)

    • Dare

      @Frosty Yeop for sure. You can still see the code if you click and hold the mouse down at the beginning of the line and drag down. This selects the entire line. You can then paste it into notepad or whatever to see it.

  • Pingback: 15+ Useful PHP Components, Techniques and Tutorials

  • http://www.blog.cheshmehregi.com Cheshmehregi

    Hello
    Thanks for the information ,
    but it didnt work for me , i am trying to combine 3 css in to one – but this method didnt work – can you please tell me how to compress / combine the css files in tho one?
    thanks

  • Gunnar Ileson

    Here at work the third method would be rerwritten for lowering the traffic. It will send the css data to the client on each request when it’s not in separate css files that can be cached by the client.

    And the two first methods would also be rewritten, so php don’t have to compress the file on each request but somehow cahce the compressed vesion.

  • Nina

    thank you so much for this excellent post! The Reinhold Weber method is awesome!

  • John

    I use a method in my websites where everything goes through index.php. I use buffering to organize code and dynamically add only the styles I need. I have many, many style sheets, one that all pages use, one for the login page, the landing page etc. In my Styles folder I have a php file titled “StyleMaster.php” which has the following code.

    I then reference “StyleMaster.php?file=Login.css” in my head element on the HTML.

    One small tidbit I have not figured out how to work around is the potential to have lines commented out “//” which I still do in my css from time to time though I probably shouldn’t. I’m not very good at regex…you might recognize it as coming from that third method :P.

  • John

    hmmm, php didn’t print.

    Pastebin: http://pastebin.com/mLSepiFf

  • John

    Aha! Finally got the regex resolved (mainly for js compression since // in css technically is a syntax error…)

    $buffer = preg_replace(‘/\/\/.+?$/m’, ”, preg_replace(‘!/\*[^*]*\*+([^/][^*]*\*+)*/!’, ”, $buffer));

  • kathy

    hi jean baptiste, did you ever come up with a solution that also caches this minified css?

    • kathy

      for anyone looking for an easy fix… the plugins wp-minify and autoptimize both combine, compress (and cache i think) all your css automatically.

  • Artemis

    Hello guys,

    When i add this, my site menu gets ruined, and this is because when i click to read the css file, i get this error:

    SHTML Wrapper – 500 Server Error

    Anyone got an idea?
    Thanks,
    Artemis

  • http://www.shertonenglish.com/ Sherton

    @Artemis 500 Server Error is usually a php syntax error.

    Great material. Dealing with this for weeks and now trying with Google Minify.

  • http://www.konturart.net kontur

    You can extend method three to dynamically include files by handing the file some parameters like…

    … and then seperating the file names for inclusion in the php like …

    $css_files = explode(” “, $_GET['files']);
    if (!empty($css_files)) foreach ($css_files as $css) {
    if (!empty($css)) include $css;
    }

    That way you can include different css files, if you have your website’s css divided by sections, for example. Mind your caching setting though with that.

  • John

    Method 3 has the disadvantage that it also strips spaces inside strings (like in content properties) breaking your styles.

  • http://www.jabari.net Jabari

    Maybe I’m missing something…

    Why use PHP to compress a static file each and every call??? Why not just include a CSS file that has been pre-compressed and save the processing time all altogether?

  • http://thesischildtheme.com serge

    great! exactly what i needed ! Thanks a lot.

    A small modification to compress function in the last method like this would do the job even better :

    function compress($buffer) {
    /* remove comments */
    $buffer = preg_replace(‘!/\*[^*]*\*+([^/][^*]*\*+)*/!’, ”, $buffer);
    /* remove tabs, spaces, newlines, etc. */
    $buffer = str_replace(array(“\r\n”, “\r”, “\n”, “\t”, ‘ ‘, ‘ ‘, ‘ ‘), ”, $buffer);
    /* “control” shots */
    $buffer = str_replace(‘; ‘, ‘;’, $buffer);
    $buffer = str_replace(‘: ‘, ‘:’, $buffer);
    $buffer = str_replace(‘{ ‘, ‘{‘, $buffer);
    $buffer = str_replace(‘ }’, ‘}’, $buffer);
    $buffer = str_replace(‘;}’, ‘}’, $buffer);
    return $buffer;
    }

    • http://www.paulhanak.com Paul

      Hey Serge, can you explain the control shots for me? It seems like you are just removing spaces. Doesn’t it already do that? I like there your heads at though…..

  • http://TestMy.net Damon

    I like the The Reinhold Weber method… combined with a .htaccess rule to make the file appear to be a root located normal .css file.

    RewriteRule ^style.css$ /path/to/php/css-min.php [L]

    Works beautifully for me. I think I may modify this a bit to accept file name variables so I use the one php script to compress other css files… which I defer from parsing until needed.

    … okay, fine, I’ll build it now and share it…

    // useage in .htaccess RewriteRule ^style.css$ /path/to/css/css-min.php?cssFileName=tmn_12 [L]

    header(‘Content-type: text/css’);
    ob_start(“compress”);
    extract($_GET);
    $cssFilePath = “/path/to/css/”;
    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;
    }

    include(“$cssFilePath$cssFileName.css”);

    ob_end_flush();

    Just edit the path to where your css is then add the variable to the rewrite rule. I made it so the extension is added in the php file so you only have to enter the file name as the variable, minus the .css extension.

    Using it this way you can compress as many files as you want… separately… with only one php script. Fits my needs better I hope it does for someone else too.

    - Cheers!
    - Damon

  • http://...... mersed

    Third one is good indeed..
    But i do not recommed using ” ” (two wite space removal) (expecialy if you applying something like this on .css file wich you wrote before, and have a lot of rules and lines).
    $buffer = str_replace(array(“\r\n”, “\r”, “\n”, “\t”, ‘ ‘, ‘ ‘, ‘ ‘), ”, $buffer);

    .some_class a {will result in .some_classa and you do not have this class}

    If you are writting your css file from scratch then you know where tricky part is and what you can and what cannot use. ;)

  • Sasha

    I am working on my small CMS because I’m to frustrated with Drupal, Joomla… bloating, to much db request, to much queries etc.. All time hundreds of methods ask for answer what can be configured on just one click “SAVE CONFIGURATION”, and that will make less request, and queries..

    Also with CSS, why in every HTTP request do this: preg_replace(‘!/\*[^*]*\*+([^/][^*]*\*+)*/!’, ”, why not create button in admin panel “Minimize and clean all your CSS and JS”-YES —> and AFTER that use CSS and JS COMBINER (depends on page request). In Combiner is fread()… and next step is CACHE mechanism…

    If dveloper/admin wants to edit some css, or add new component to it’s platform, just go again to step “Save and minify CSS and JS”. That’s is what will do my CMS. Why to do every time same thigs on “the fly” (preg_replace(‘!/\*[^*]*\*+([^/][^*]*\*+)*/!’, ”). I’m sorry but I don’t like that principe.

    Best regards!
    … and this is very nice discussion

  • Max P

    Excellent! Just what I was looking for… you must be a mind reader!

  • Felipe

    In PHP, use Minify library, is better way to compress and join css or js files.

  • http://www.a1brandz.com A1brandz

    How this will affect website performance negative or positive way? I think compressed css pages takes less time thus makes web page load faster then uncompressed css.

  • http://deal321.com Andy

    Hello,
    PLEASE someone could explain me how and where to insert the Reinhold Weber method ?!
    into the header file, into the head of each css file or just a single file, I dont get it ;)
    Thnaks so much

  • http://royal-cleaning.co.uk Deni Ivanov

    I have a problem with compressing the CSS this way.When I put the following code

    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}\.php -f
    RewriteRule ^(.*)$ $1.php
    # Replace html with your file extension, eg: php, htm, asp

    RewriteEngine on

    RewriteCond %{THE_REQUEST} /index\.php? [NC]
    RewriteRule ^(.*/)?index\.php?$ /$1 [R=301,L]

    In my code the css files that I use get redirected and do not work.Is there a way to work around this?

  • Kevin

    Neat article,
    Reinhold Weber’s was simular to what I had in mind myself. It really helped me making it :D

    I think though, that there may be a couple of mistakes in the str_replace. When looking at the whitespaces:
    - two whitespaces are removed
    - four whitespaces are removed
    - four whitespaces are removed

    It seems three whitespacing accidently became four. Also, two times two is four, so removing four whitespaces when already removing two whitespaces is quite redundant.

    Furthermore, but this is just my opinion, rather than removing multiple whitespaces I’d replace them by one. If someone had a whitespaces intended, but by accident put two whitespaces, then there would be none. Of course this would result in more code, but I rather keep small mistakes in mind than having fewer characters.

  • Will Fischer

    Very interesting! I usually use a online tool (like http://www.giftofspeed.com/css-compressor/ or http://tools.arantius.com/css-compressor ) for compressing CSS but I didn’t know you can basically do it so easily with your own PHP scripts.