Compress CSS using PHP

October 9th, 2011 by Tony de Jesus

image of a compressor with a CSS boxOne of the most important things to consider when creating a website is its loading time. The loading time of a website is as important as its functionality. What’s the point in having a great website if it takes too long to load? Who wants to wait for it? There are a lot of resources that you can optimize on your website and one of them is the CSS code. In this post I’ll show you a way to compress your CSS code using PHP.

There are some methods that require changing the file extension from .css to .php. However, with this method, you don’t need to do that. First of all, add the following PHP code at the very beginning of your CSS file:


if(extension_loaded('zlib')){

     ob_start ("ob_gzhandler");

     header("Content-type: text/css; charset: UTF-8");

     header("Cache-Control: must-revalidate");

     $expires = "Expires: " .

     gmdate("D, d M Y H:i:s",

     time() + (60 * 60)) . " GMT";

     header($expires);

}

Now we need to tell the web server to process our CSS file as a PHP file. We can use a .htacess file to do that:


<Files yourcssfilename.css>
AddType application/x-httpd-php .css
</Files>

Don’t forget to change “yourcssfilename.css” to the name of your CSS file.

For some reason, in my Media Temple host this directive does not work. Instead of that you can use:


<Files yourcssfilename.css>
SetHandler php-script
</Files>

Here is a screenshot of Firebug’s network tab. As you can see, the browser is loading a CSS file called styles.css and its size is 24.4KB.

Screenshot of firebug network tab

Here is the same file, but using the compression method described above. Now the size of the file is 5.2KB.

Screenshot of firebug network tab

Do you know a better method to do this? Any ideas that contribute to optimize CSS loading? Please share your thoughts in the comments section.

, ,

 
 
 

One Comment

  1. Duarte

    Nice article! optimization is something that we need to emphasize more, this way we produce sites with less impact in users, faster loading, etc..

Trackbacks

Leave a Reply to Duarte