Compress CSS Files using PHP

Here is the nice trick to compress your css files using PHP in easy way. For this trick you do not need to rename your .css file .php files.

Currently I was seaching for the CSS compression tricks and found several methods. Some of those methods needs to rename my .css files to .php files and place the compression code in all file.

But in trick you do not need to rename the css files and you can get it done by one PHP file only.

Let’s see how it works:

You need to create one PHP and place the below code into that PHP file.

<?php
// This defines the header type
header("Content-type: text/css");
 
// Start the output buffer
ob_start("compress_css");
 
// Function which actually compress
// The CSS file
function compress_css($buffer)
{
 /* remove comments */
 $buffer = preg_replace("!/\*[^*]*\*+([^/][^*]*\*+)*/!", "", $buffer) ;
 /* remove tabs, spaces, newlines, etc. */
 $arr = array("\r\n", "\r", "\n", "\t", "  ", "    ", "    ") ;
 $buffer = str_replace($arr, "", $buffer) ;
 return $buffer;
}

/* include all CSS files */
include("style.css");
include("fonts.css");
include("print.css");

// Flush the output buffer
ob_end_flush();
?>

Update:

$lastCssModificatedAt) { $lastCssModificatedAt = $cssModificatedAt; } } if(filemtime($cacheFilename) >= $lastCssModificatedAt) { return true; } } return false; } /* include all CSS files */ // include("style.css"); // include("fonts.css"); // include("print.css"); $cssFiles = array("style.css", "fonts.css", "print.css" ); // This can be changed whatever you want $cacheFilename = md5(implode("",$cssFiles)).".css"; $cssCompressed = ""; if(!checkCacheIsOk($cacheFilename, $cssFiles)) { $cssCompressed = buildCache($cssFiles); writeCache($cacheFilename, $cssCompressed); } else { $cssCompressed = file_get_contents($cacheFilename); } echo $cssCompressed;
<?php

// This defines the header type
header("Content-type: text/css");
 
// Function which actually compress
// The CSS file
function compress_css($buffer)
{
 /* remove comments */
 $buffer = preg_replace("!/\*[^*]*\*+([^/][^*]*\*+)*/!", "", $buffer) ;
 /* remove tabs, spaces, newlines, etc. */
 $arr = array("\r\n", "\r", "\n", "\t", "  ", "    ", "    ") ;
 $buffer = str_replace($arr, "", $buffer) ;
 return $buffer;
}

/**
 * Builds CSS cache file
 * @param array $cssFiles
 * @return string
 */

function buildCache(array $cssFiles)
{
    $cssString = "";
    foreach($cssFiles as $cssFile)
    {
        $cssString .= file_get_contents($cssFile);
    }
    $cssString = compress_css($cssString);
    return $cssString;
}

/**
 * Writes the cache into file
 * @param string $cacheFilename
 * @param string $cssCompressed
 */

function writeCache($cacheFilename, $cssCompressed)
{
    $f = fopen($cacheFilename, "w");
    // lock file to prevent problems under high load
    flock($f, LOCK_EX);
    fwrite($f,$cssCompressed);
    fclose($f);
}

/**
 * Compare the modification time of cache file against the CSS files
 * @param type $cacheFilename
 * @param array $cssFiles
 * @return bool
 */

function checkCacheIsOk($cacheFilename, array $cssFiles)
{
    if(file_exists($cacheFilename))
    {
        $lastCssModificatedAt = 0;
        foreach($cssFiles as $cssFile)
        {
            $cssModificatedAt = filemtime($cssFile);
            if($cssModificatedAt > $lastCssModificatedAt)
            {
                $lastCssModificatedAt = $cssModificatedAt;
            }
        }

        if(filemtime($cacheFilename) >= $lastCssModificatedAt)
        {
            return true;
        }
    }
    return false;
}

/* include all CSS files */
// include("style.css");
// include("fonts.css");
// include("print.css");

$cssFiles = array("style.css", "fonts.css", "print.css" );

// This can be changed whatever you want
$cacheFilename = md5(implode("",$cssFiles)).".css";

$cssCompressed = "";

if(!checkCacheIsOk($cacheFilename, $cssFiles))
{
    $cssCompressed = buildCache($cssFiles);
    writeCache($cacheFilename, $cssCompressed);
}
else
{
    $cssCompressed = file_get_contents($cacheFilename);
}

echo $cssCompressed;

This method uses the output buffer function to make it work. From here You can know about Output Buffer Explained.

Note: You do not need to rename you .css files to .php.

Related Posts

Written by Avinash

Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.

View all posts by: