views:

163

answers:

2

I'm using the scripts below to gzip some CSS and JS files. It works nice - except for serving JS files with the wrong content-type (and not the appropriate application/x-javascript). How could I improve the PHP code in order to serve the right content-type? Thanks!

.htaccess:

AddHandler application/x-httpd-php .css .js
php_value auto_prepend_file gzip.php

gzip.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);
?>
+4  A: 

You could check the ending of the requested URL path:

$_SERVER['REQUEST_URI_PATH'] = strtok($_SERVER['REQUEST_URI'], '?');
$extensionToType = array(
    '.css' => 'text/css;charset=utf-8',
    '.js'  => 'application/javascript;charset=utf-8'
);
$extension = strrchr($_SERVER['REQUEST_URI_PATH'], '.');
if (isset($extensionToType[$extension])) {
    header("Content-type: ".$extensionToType[$extension]);
} else {
    header("Content-type: application/octet-stream");
}
Gumbo
+1 Nice answer Gumbo!
Doug Neiner
I replaced line 3 of my original gzip.php script with your proposal, but when executing the script I get this error: syntax error, unexpected T_STRING, expecting ')' in /is/htdocs/wp1143954_G1SAXKG9IV/www/files/gzip.php on line 5In my script line 5 is: '.css' => 'text/css;charset=utf-8',
univers
@univers: Did you replace your entire third line with my lines?
Gumbo
Looks like the error was somehow caused by copy/paste. I did not find out what the actual error was, but I after I deleted and re-typed lines 3, 4, 8 and 10 of your code by hand everything works fine. Thank you very much!
univers
@univers: You should use an editor that supports syntax highlighting.
Gumbo
I use TextWrangler, which supports syntax highlighting. Therefore I guess it was a copy/paste/invisible characters problem maybe.
univers
A: 

You could also check the mime-type thanks to FileInfo rather than using the extension.

Pikrass