Combine & Minify CSS with PHP

A fast website equals a good user experience. It also pleases search engine spiders. Using a little PHP you can combine & minify all of your CSS files on-the-fly. This not only reduces the overall filesize, but also minimises HTTP requests.

How do we do it?

<?php
header('Content-type: text/css');
ob_start("compress");

    function compress( $minify )
    {
        /* remove comments */
        $minify = preg_replace( '!/*[^*]**+([^/][^*]**+)*/!', '', $minify );

        /* remove tabs, spaces, newlines, etc. */
         $minify = str_replace( array("rn", "r", "n", "t", '  ', '    ', '    '), '', $minify );

        return $minify;
    }

    /* css files for combining */
    include('reset.css');
    include('application.css');
    include('responsive.css');

ob_end_flush();

Usage.

Create a file with the code above and save it as minified.css.php, then simply link to that file as you would normally for your CSS file:<link href="assets/css/minified.css.php" rel="stylesheet">

All the CSS files you reference inside the script will be combined & minified at run time.

Conclusion.

This not only makes your web site faster, it also allows you to work with multiple files in development without having to manually compress each before pushing to production.

sco://

About Me

Designer. Developer. Hacker. Senior Reviewer / Content Specialist @envato