CSS & Javscript File Compression with PHP

Compressing your JavaScript and CSS files is a great way to save bandwidth and reduce the time your pages take to load. If you have one or two small style sheets it doesn’t really matter that much. Larger sites seem to use a lot of CSS and JavaScript files. CSS, being the hash pipe of web design these days, is used like toilet paper.

Heres an quick and effective effective technique that you can use in PHP to compress most of your files.

1. Rename your .css file extension to .php, unless your *.css files have been set in .htaccess to execute PHP. It’s generally a bad idea to mod *.css files to run as PHP.

2. Open up one of your files using a text editor(NotePad, KWrite, etc) and add open a PHP tag on the first line:

<?php
header('Content Type: text/css;'); // The browser recognize this PHP file as a "text/css" mime type.


// Check for any problems
if(function_exists('ob_start'))
{
if(!function_exists('ob_gzhandler'))
{
die('Error: Gzip handler is not available, please make sure it is installed');
}
}
else
{
die('Output buffering is not available.');
}
/* Gzip handler is what compresses the file content */
ob_start('ob_gzhandler'); // Start an output buffer, callback Gzip Handler
?>
/* Css code goes here */
.MyCSSClass
{
padding: 0;
}
<?php
// One more thing, flush the buffer
ob_end_flush();
?>

3. Save it, and open it in a browser to make sure it works.

If that works, you did it! Enjoy!

Leave a Reply