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.
White Men Can’t Jump the movie
If that works, you did it! Enjoy!
Tags: Apache, callback function, CSS, Executing CSS Files as PHP Files, gzip, JavaScript, output buffer, PHP, php compression, php css tag, php file compression, Server Side Compression, web development
I want to sincerely thank you for being a part of and reading this blog. It is only through your support that I am able to continue to provide valuable content to my readers.
If you would like to show your appreciation please support my efforts by making a small donation
