CSS headers for gzipped php files

design

#1

Odd one, I hope someone can help.

I’m using a PHP file to generate CSS, which I want to gzip before serving.

Here’s some example code:
myCSS.php
[php]

<?php header('Content-type: text/css'); ob_start("ob_gzhandler"); ?>

body:{color:red;}
[/php]

Now, I know I don’t need the ob_gzhandler, as DH gzips. My problem is that if I include the text/css header then nothing is gzipped. If I leave it out then the file is compressed nicely, but the browser won’t recognise the css rules.

This is cross browser, and I’ve tried all sorts of combinations of different gzip methods, and the order of the headers but I just can’t get it to work. I’ve tried a link rel=stylesheet and an @import, and even meddled with .htaccess!

If I add the css header it won’t compress, if I leave the header out it will compress but will not be recognised as CSS.

(I have the same issue with javascript files, but at least the browser will still eventually figure out that it’s js…)

Is this a DH peculiarity or have I done something very silly?


#2

pop this in your .htaccess:

<IfModule mod_deflate.c>
  <FilesMatch "\.(css|js|x?html?|php)$">
    SetOutputFilter DEFLATE
  </FilesMatch>
</IfModule>

Might work


#3

Or, simpler:

(The text/html type is already specified in the server configuration, so you don’t need to repeat it.)


#4

Genius - thank you people!

My CSS is now compressed and recognised as CSS!

Doesn’t work for the javascript though:

myJS.php
[php]

<?php header('Content-type: application/x-javascript'); ?>

var stuff=ting;
[/php]

If I have the header in it doesn’t deflate, if I take it out it doesn’t deflate or have the correct mime-type. It doesn’t massively matter as I can deflate with zlib.output_compression and the browser will figure out that it’s javascript but it’s good to get these things right if we can.

Thank you for your help!


#5

I believe that AddOutputFilterByType determines the “type” of a file based on its extension, not on the final value of the Content-Type header, as Apache sets up output filters before it knows what the headers on the output will be. You’ll need to use a workaround like the one posted by bobocat above if the extension doesn’t match the final MIME type.


#6

I get you. Thanks again!


#7

not sure exactly what your main goal is, but if it’s just compression, I’ve tweaked this code to work with all CSS and JS on my site. I don’t put it in the CSS, but read ad the CSS files requested into this compressor and return the output:

http://www.ibloomstudios.com/articles/php_css_compressor/

that way CSS stays CSS and avoids confusing the IDE