Code Snippets Gallery

Blog > Code Snippets > CSS > Compress CSS with PHP Submit one!

Compress CSS with PHP

Start your CSS files with this PHP (and name it style.php):

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

body { color: red; }

Then call your CSS with the PHP file name:

<link rel='stylesheet' type='text/css' href='css/style.php' />

Responses

  1. Ben says:

    Some older browsers choke when CSS files don’t have the .css extention. It’s the same with Javascript files.

    Perhaps use .htaccess to rename it to style.css

  2. TeMc says:

    @Ben: Or rename the file to .css and use .htaccess to interpretate is as PHP ;-)

  3. TeMc says:

    @Ben: Or rename the file to .css and use .htaccess to interpretate it as PHP ;-)

  4. Roflo says:

    I believe it’s good practice to call ob_flush(); at the end of your script.

  5. DougS says:

    how do you know so much stuff

  6. I’m glad to see my submission got up on the site.

  7. Hassan says:

    I get “Cannot modify header information” error. Any idea?

    • David says:

      You may be outputting something before the call to header().

      Usually this is because of a new line or space before the very first <?php tag

Leave a Comment

Remember:
  • Be nice.
  • Wrap all code in <pre> and <code> tags. (single or multiple lines) and escape it first (turn <'s into &lt;'s).
  • You may use regular HTML stuff like <a href="">, <em>, and <strong>