Compress CSS Files using PHP

  • Avinash
  • 12
  • Aug 27, 2011
  • Tips & Tricks

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:

  • Pingback: xhtml css templates – Compress CSS Files using PHP | Expert PHP Developer | XHTML CSS - Style sheet and html programming tutorial and guides

  • http://www.beyta.net Beyta

    sorry… when need to load that file? need to place in head or just include on the load page?

    • http://www.xpertdeveloper.com Avinash

      you can simply include the file like

      // in this file you can place the above code.
      include(“cc_compress.php”);

  • Karoly Bujtor

    This code can be enhanced some caching to improve performance.

    Maybe you can replace output buffering and include() calls with file_get_contents() to prevent code injection through css files.

    • http://www.xpertdeveloper.com Avinash

      Suggestions are most welcome :)
      Can you please share the code which you are suggesting?

      • Karoly Bujtor

        Well… I thought about something like that:

        • http://www.xpertdeveloper.com Avinash

          Hi Karoly,

          Thanks for the suggestion. I have placed your code in post content as a update.

  • http://xvir0e5x.blogspot.com vir0e5

    like this…. i want to your share using form…. to comprees it,,,, :)

  • Thomas

    Hi ! This code is awsome to use , thank you . First time all worked as ecpected.
    At the moment, i use your code as follow (header has been removed to inline the css):

    ob_start();

    echo “”;
    include(“/www/whatever/css_compress.php”);
    echo “”;

    ob_end_clean();

    This works perfect and now and JS should be compressed same way.

  • Thomas

    ok, your script removed the text behind echo

    echo ” ” ;

  • http://www.l33tnews.com/ Andrew Barfield

    Awesome!!

    I replaced:
    …with only:

    Your script eliminates 2 HTTP calls and compresses the single call while reducing CPU use on future calls via server-side cache.

    Please note: You need to make the folder where the PHP script is writable for the script or the cache file will not be written (but the output is still echoed to the browser).

    Thank You!

  • Sam

    you system fail with this code:
    is possible upgrade please?

    $css=’h2{
    color:#aa0000;
    text-shadow:#aa0000 1px 1px 2px;
    /*
    /* W3C no acepta esto pero funciona con IE
    filter:/*progid:DXImageTransform.Microsoft.dropShadow(color=#000,offX=99,offY=99)*/
    progid:DXImageTransform.Microsoft.Alpha(opacity=99)
    progid:DXImageTransform.Microsoft.Blur(pixelradius=1.4,enabled=’true’);
    /*font-size:5em;*/
    */
    */
    font-size:12em;
    }
    .perdido{
    /* perdido o cualquier otro estilo se pierde… */
    color:#fff;
    }
    ‘;
    $css=preg_replace(‘!/*[^*]**+([^/][^*]**+)*/!’,”,$css);
    echo $css;