PHP

PHP Code to Combine and Compress CSS

A couple of Google updates ago they worked on page loading speeds, so if your page loaded faster then your website will be ranked higher.

Easy ways to improve on your website speed is:

  • Reduce the size of the CSS and JS files.
  • Reduce the number of HTTP requests.

Therefore this PHP snippet will do both for your CSS Files. Create a PHP file in the same location as your CSS files. Insert the following snippet in the PHP file and change the include of the CSS files to match yours. Then in your HTML instead of calling each of the CSS files replace these with a link to the PHP file.

When the PHP file is called it will change the HTTP header to text/css making the server think this is a CSS file. Then we can start buffer of the output by go through a function called compress. This function will then go through all the contents of the buffer and remove all comments and remove all spaces and new lines in the content and then output this.

The output will be output by this PHP file as a CSS files therefore making the browser think this is a CSS file and will process it as normal but all your CSS has now been compressed by removing comments and whitespace, and all the CSS files have been joined into one HTTP header request.

header('Content-type: text/css');
ob_start("compress");
function compress($buffer) {
  /* remove comments */
  $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
  /* remove tabs, spaces, newlines, etc. */
  $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
  return $buffer;
}

/* your css files */
include('master.css');
include('typography.css');
include('grid.css');
include('print.css');
include('handheld.css');

ob_end_flush();
Back to top

Gain access to all tutorials

  • Premium tutorials covering WordPress, Laravel and VueJS
  • Download premium content
  • Download premium WordPress plugins
  • Only $5 a month

Join Paulund