Code Snippet
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' />
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
Anyway nobody cares about old browsers when developing Web sites.
@Ben: Or rename the file to .css and use .htaccess to interpretate is as PHP ;-)
@Ben: Or rename the file to .css and use .htaccess to interpretate it as PHP ;-)
I believe it’s good practice to call ob_flush(); at the end of your script.
how do you know so much stuff
I’m glad to see my submission got up on the site.
I get “Cannot modify header information” error. Any idea?
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
Thanks for the snippet. The line
<pre>header(“Content-type: text/css; charset: UTF-8″);</pre>
should be
<pre>header(“Content-type: text/css; charset=UTF-8″);</pre>
What are the advantages if i compress css?:)
i think you can also use gzip or defalte mod options if you are using apache server.
What is the uses ?
-thanks in advance.. :)
What are the advantages of it? I am using Minify stuff?
you could use it like this:
<?php $base_color = "#COFFEE"; ?> a { color: <?=$base_color?>; }This script has disadvantages. The main disadvantage is caching.
On first visit, php will set expire date to “future”, but… if you make change into the CSS, will not reflect to returning visitors, because they already have cached CSS.
DigWP
A book and blog co-authored by Jeff Starr and myself about the World's most popular publishing platform.
Quotes on Design
Design, like Art, can be an elusive word to define and an awfully fun thing to have opinions about.
HTML-Ipsum
One-click copy to clipboard access to Lorem Ipsum text that comes wrapped in a variety of HTML.
Bookshelf
Hey Chris, what books do you recommend? These, young fertile mind, these.