2 min read

Compressing CSS files with PHP

When using a refined and visually appealing website design, CSS files can become quite large, leading to longer load times. Below are three methods to compress CSS files using PHP.

Method 1

To implement this method, first rename your .css file to .css.php and make sure to import it in your HTML file with the new name:

<link rel="stylesheet" type="text/css" media="screen" href="style.css.php" />

Next, edit the CSS file and add the following code at the beginning:

<?php if (extension_loaded('zlib')) { ob_start('ob_gzhandler'); } header("Content-type: text/css"); ?>

Then, append the following line at the end of the file and save it:

<?php if (extension_loaded('zlib')) { ob_end_flush(); } ?>

Method 2

This method works similarly to the first one. Rename the .css file to .css.php and insert the following code at the beginning:

<?php
  ob_start("ob_gzhandler");
  header("Content-type: text/css; charset=UTF-8");
  header("Cache-Control: must-revalidate");
  $offset = 60 * 60;
  $expire = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
  header($expire);
?>

The only difference from the first method is that you only need to add this code at the beginning of the CSS file.

Method 3

This is my favorite method for CSS compression.

<?php
  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;
  }
  header("Content-type: text/css");
  ob_start("compress");
  /* Include CSS files */
  include('master.css');
  include('typography.css');
  include('grid.css');
  include('print.css');
  include('handheld.css');
  ob_end_flush();
?>

Why do I prefer this method? Because unlike the previous ones, you don’t need to rename the CSS file to .php. This method efficiently removes comments, tabs, spaces, and other unnecessary characters, making it an excellent choice for new projects.