PHP
Article

Automatic CSS3 Prefixer and Compressor

By Fibi Wolulas

There are many ways to compress CSS files or automatically generate browser-specific CSS3 prefixes, but usually extra tools are used which is very annoying. I’d like to show you how such tasks can be done using only PHP. In this article we’ll see how to:

  • Generate CSS3 properties with browser-specific prefixes so that we don’t have them all by hand
  • Concatenate all the CSS files and strip out comments and unnecessary white space to reduce the number of server requests and decrease the page’s load time
  • Perform the process on-the-fly when the web page is requested

Here’s an example that shows just how easy the end result will be to use.

In the CSS, the browser specific prefix is replaced with an underscore like this:

_border-radius: 10px;

The code will generate a complete list of properties like this:

-o-border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;

Then, in the HTML, a link is written like this to import the styles:

<link rel="stylesheet" href="css/css.php?f=css_file1|css_file2|css_file3">

With the single link element, three CSS files will be loaded as one. The css.php script will read in the files that are listed (css_file1.css, css_file2.css, and css_file3.css), combine them, and return them as a single file.

It looks pretty easy to use, right? So with out further ado, let’s start writing some code!

Writing the Code

Go ahead and create the file css.php with the following code:

<?php
$files = explode("|", $_GET["f"]);

$contents = "";
foreach ($files as $file) {
    $contents .= file_get_contents($file . ".css");
}

preg_match_all('/_[a-zA-Z-]+:s.+;|[a-zA-Z-]+:s_[a-zA-Z].+;/',
    $contents, $matches, PREG_PATTERN_ORDER);

$prefixes = array("-o-", "-moz-", "-webkit-", "");
foreach ($matches[0] as $property) {
    $result = "";
    foreach ($prefixes as $prefix) {
        $result .= str_replace("_", $prefix, $property);
    }
    $contents = str_replace($property, $result, $contents);
}

$contents = preg_replace('/(/*).*?(*/)/s', '', $contents);
$contents = preg_replace(array('/s+([^w'"]+)s+/', '/([^w'"])s+/'), '\1', $contents);

header("Content-Type: text/css");
header("Expires: " . gmdate('D, d M Y H:i:s GMT', time() + 3600));
echo $contents;

The code first receives the list of CSS files to be processed as a string from the URL parameter (accessible in PHP as $_GET["f"]). Each file is separated with a pipe-character. The explode() function splits the string on the pipes returning an array of filenames.

The function file_get_contents() gets the contents of each file which is appended, one by one, to the variable $contents.

After the contents of the CSS files has been retrieved, the next step is to find any CSS properties that start with an underscore and replace them with the browser-specific prefixed properties. The function preg_match_all() finds all the parts in the text that match the regular expression and places the matches into $matches[0] as an array.

I won’t explain why $matches has the array index 0 because you can read a clear explanation about the function in the PHP Manual. Rather I’d like to focus on explaining the flow of our program.

This image explains the pattern of the regular expression:

The array $prefixes contains an array of browser-specific prefixes; you can add more prefixes, or even remove some, depending on your needs. Each property definition in $matches[0] will be transformed into a set of CSS3 properties with browser-specific prefixes. The code iterates each property and creates a result buffer, replaces the underscore in the property with the browser-specific prefix and pushes the result in the the buffer, and then replaces the original property in in the text with the contents of the buffer.

After expanding the browser-specific prefixes is done and they have been merged back into $contents, the script strips out any comments in the content to reduce its size. This image explains the relevant regular expression:

Then another regular expression removes any unnecessary whitespace and new lines to further reduce the size of the content.

Parts that match with regular expression will be replaced by characters inside the bracket, for example:

Finally the CSS stored in $contents is ready to be sent. The first header() call informs the browser that the output should be treated as a CSS file. The second header() call tells the browser that this file expires in one hour, so the browser will cache it for an hour and use the cached copy instead of requesting it again from the server.

Using the Script

I’d like to give you a simple usage example for script that we’ve just made. Put the css.php into your css directory, along with these three CSS files.

The first file is header.css:

#header {
  width: 800px;
  height: 100px;
  padding: 20px;

  _border-radius: 10px;
  _box-shadow: 0px 0px 10px #000000;
  background: _linear-gradient(#D30000, #3D0000);
}

The second file is center.css:

#center {
  width: 800px;
  height: 400px;
  padding: 20px;
  margin: 20px 0px;

  _border-radius: 10px;
  _box-shadow: 0px 0px 10px #000000;
  background: _linear-gradient(#8ED300, #213D00);
}

The third file is footer.css:

#footer {
  width: 800px;
  height: 100px;
  padding: 20px;

  _border-radius: 10px;
  _box-shadow: 0px 0px 10px #000000;
  background: _linear-gradient(#006ED3, #00203D);
}

Look at how the CSS3 properties have been written; the ones that would have a browser-specific prefix are given only once and have an underscore in front of them.

Next, create the file index.html that will use the styles.

<!doctype html>  
<html lang="en">  
 <head>  
  <meta charset="utf-8">  
  <title>example</title>  
  <link rel="stylesheet" href="css/css.php?f=header|center|footer">
 </head>  
 <body>
  <div id="header">header</div>
  <div id="center">center</div>
  <div id="footer">footer</div>
 </body>
</html>

Look at the href attribute in the link tag. Every CSS filename is separated by a pipe.

Conclusion

In this article I showed you how to automate some common manipulations of CSS using PHP. The script relies heavily on regular expressions, a very powerful language that allows us to manipulate string however we see fit. Overall, the script is very simple but it offers many benefits. Try using it in your next project.

Image via 1xpert / Shutterstock

More:
  • http://www.mymmcloud.com Zaw Myo Htet

    It is a nice tutorial.

    • Fibi Wolulas

      Thanks Zaw, you should try it :)

  • Glen

    Why not use browser detection and only include the vendor prefixes required, would lower the bloat of the css…

    • Fibi Wolulas

      You’re right, that’s a good idea.
      I never thought about that, I just followed the usual pattern :D

  • http://georgedina.ro George Dina

    I had in mind to do something like this for a while, now I have reasons to be lazy, you already made it :)
    Nice work, you thought at everything, congratulations!

    • Fibi Wolulas

      Thanks George, I hope this can be useful for you :)

  • Tjorriemorrie

    I really like this article! Anything similar possible for js? Or is the minifying too complex?

    • Fibi Wolulas

      Maybe the minify part of this code can be used for javascript. But I think it needs some addition, we have to examine further.

  • Martin

    It would be better with a file caching.

  • Xojins

    Wouldn’t this defeat the purpose of caching? You are always dynamically building he css and sending it to the client.

    • Fibi Wolulas

      But it’s just once per client, because after that the css is stored in the browser cache.
      It’s just a php script without connecting to the database, it’s very fast. And remember, this code makes CSS requests combined into one.
      But of course if you use this script with server side caching, it will be better :)

  • http://bit.ly/codecanyon-m4n3z40 Allan Baptista

    I’ve came up with a similar idea a while back, it works really well for most projects that I’ve used it. Then I’ve came across Prefixr and I started using it with Curl, works perfectly! Do you know this service?

    • Fibi Wolulas

      in terms of performance, I think this method is not good. prefixr use the parser, and you parsing the web with curl.

  • http://www.gafitescu.ro Daniel Gafitescu

    Or you can use or Less or Sass ( http://lesscss.org/ , http://sass-lang.com )

    • Fibi Wolulas

      as far as i know, sass/less can’t do autoprefix. From many sample across the web, they usually write something like this to deal with CSS3:

      #element_id ($radius: 10px){
      -webkit-border-radius: $radius;
      -moz-border-radius: $radius;
      -o-border-radius: $radius;
      border-radius: $radius;
      }

      CMIIW.

      • http://ramonlpenta.com Ramono

        This is why they have mixins, that take care of all prefixing part. It also allows you to have filters for IE and you just need to do: @include radius(10px);
        There’s also a whole lot of benefits with it, like extend rules, nested rules, variables, etc.
        Interesting script though :)

  • Alex Gervasio

    Whilst the script’s logic looks in general good, still makes you deal with the hassles of proprietary prefixes, which are just used for parsing. Definitively, not an approach to praise about. It’s a lot more preferable to generate “standard” CSS, and use a well-trusted minifier, prefixer like Prefixr http://prefixr.com/ or Lea Verou’s little gem -prefix-free http://leaverou.github.com/prefixfree/
    Keep up the good work.

    • Fibi Wolulas

      I think using prefixr is too hassle, because we must upload our code to prefixr. It’s not “on the fly”.
      I just found out about the -prefix-free, I think it’s very good at glance.

      I’m still not 100% sure about my script, but for many project I created, it’s work very good.

  • John

    Thanks for the article. The regex breakdown graphics were nice.

  • http://koalabs.co Carlos

    Hey man. Nice tutorial! Thanks a lot.
    But you promised to also teach us how to eliminate whitespace and unnecessary comments. I didn’t see any of that. :(

    • http://koalabs.co Carlos

      Sorry man. My bad! I found it. :)

  • David

    Finally, doing it on the server! Although a css preprocessor does this exact thing and a lot more, but those not using it, your script is rather handy. Just a thought:
    What if you used regex to detect all the css properties, which are there, which aren’t, fill in the appropriate ones, then publish?

    As well as enable capabilities for CSS PIE or anything else?
    That’s what I started working on, for the use of CSS PIE, but a scripting language would probably provide better performance (pearl, python?), and a CSS preprocessor is still better yet. Hence why I didn’t bother finishing with php or js.

    But awesome idea none the less. Cheers!

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in PHP, once a week, for free.