Combine & Minify CSS with PHP.

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.

The PHP code.

header('Content-type: text/css');

    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 */



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.


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.

If you’re already using our CSS framework Workless, then you’re probably already using this method as it is built-in.


About the Author

Designer. Developer. Hacker. OSCP trainee. Reviewer @Envato. Interested in InfoSec, CyberSec and Privacy.