Minify and Merge CSS Files with PHP

Since the loading time of a website is as important as its functionality, I have released a Simple CSS Minification in PHP solution to minimize CSS at runtime.

Minification means removing all unnecessary characters from a file while preserving basic code functions. The result is a new file that is smaller than the original but the same for the machine. The biggest advantage for small files is that it requires less bandwidth and client download is faster.

Reduce HTTP Requests

HTTP requests occur when a web browser sends a “request” to your website’s server for information on a web page. The fewer HTTP requests a website has to make, the faster the site can load. Web designers often use multiple CSS files because they are easier to manage, but this requires as many HTTP requests as CSS files.

We use PHP to merge all CSS files into one and minify it on-the-fly. This approach offers all the advantages of minimizing and none of the disadvantages such as forcing our developers to work with hard-to-read code.

Instead of going in the dangerous area of broken css related to un tested minification scripts, I will simple used the same minification approach with my previous post.

<?php
  
/* Add your CSS files to this array */
$cssFiles = array(
  "path/to/your/css/first/file.css",
  "path/to/your/css/other/file.css",
  "path/to/your/css/another/file.css",
);

// Merge files into one
$buffer = "";
foreach ($cssFiles as $cssFile) {
  $buffer .= file_get_contents($cssFile);
}

// Trim whitespace around lines
$buffer = implode("\n", array_map('trim', explode("\n", $buffer)));

// Remove empty lines
$buffer = implode("\n", array_filter(explode("\n", $buffer)));

// Remove whitespace
$buffer = str_replace(array("\r\n", "\r", "\n", "\t"), '', $buffer);

// Remove space after colons
$buffer = str_replace(': ', ':', $buffer);

// Shorten units
$buffer = str_replace('0px', '0', $buffer);

// Remove unnecessary semicolons
$buffer = str_replace(':}', '}', $buffer);

// Enable GZip encoding.
ob_start("ob_gzhandler");

// Enable caching
header('Cache-Control: public');

// Expire in one day
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 86400) . ' GMT');

// Set the correct MIME type, because Apache won't set it for us
header("Content-type: text/css");

// Write everything out
echo($buffer);
?>

How to implement?

Create a file containing the above code and save it as minified.css.php, then link to this file as you normally would 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, but it also allows you to work with multiple files in development without having to manually compress each before pushing to production.