PHP Compress CSS & JavaScript
Quick snippets for compressing CSS and JavaScript with PHP’s ob_gzhandler, which will gzip or deflate content depending on browser support.
Compress CSS content
To compress CSS content, add the following code to any PHP file (i.e., .php
extension):
<?php // compress CSS
header("content-type: text/css; charset: utf-8");
header("cache-control: must-revalidate");
$offset = 365 * 24 * 60 * 60;
$expire = "expires: ".gmdate("D, d M Y H:i:s", time() + $offset)." GMT";
header($expire);
if(!ob_start("ob_gzhandler")) ob_start();
?>
<?php // replace this line with as much CSS code as you want ?>
<?php ob_flush(); ?>
Compress JavaScript content
To compress JavaScript content, add the following code to any PHP file:
<?php // compress JS
header("content-type: text/javascript; charset: UTF-8");
header("cache-control: must-revalidate");
$offset = 365 * 24 * 60 * 60;
$expire = "expires: ".gmdate("D, d M Y H:i:s", time() + $offset)." GMT";
header($expire);
if(!ob_start("ob_gzhandler")) ob_start();
?>
<?php // replace this line with as much JavaScript code as you want ?>
<?php ob_flush(); ?>
That’s all there is to it, and to further reduce file size, you should run the actual CSS/JavaScript code through the minifier of your choice.
For more information about either of these methods, check out my articles at Perishable Press: