Hi guys,
I've been reading up on this server-side GZIP compressor thing, but it seems users on shared hosting are out of luck. Luckily though, Hostmonster allows for ZLib compression activation by throwing an editable php.ini file. But Zlib only covers PHP files, so I was looking around for a workaround and then I stumbled on this trick in David Walshe's site:
http://davidwalsh.name/css-compression-php
Basically, it says use PHP code to consolidate css files into a single file, squeeze it and take advantage of Zlib's PHP compression to deliver the CSS as a compressed file.
In my MODX installation, I added a css.css file in my css directory with the following PHP code as instructed (did a little modification here based on the comments there):
<?php
$css = '';
$root = $_SERVER['DOCUMENT_ROOT'].'/assets/path/to/your/css/'; //directory where the css lives
$files = explode(',',$_SERVER['QUERY_STRING']);
if(sizeof($files))
{
foreach($files as $file)
{
$css.= (is_file($root.$file.'.css') ? file_get_contents($root.$file.'.css') : '');
}
}
$css = str_replace(': ', ':', str_replace(';}', '}', str_replace('; ', ';', str_replace(' }', '}', str_replace(' {', '{', str_replace('{ ', '{', str_replace(array("\r\n", "\r", "\n", "\t"), "", preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css))))))));
header("Content-type: text/css");
echo $css;
?>
I added this condition to my htaccess (top most before rewriteengine is turned on) to treat the css.css file as a php file and interpret it as such:
<FILES css.css>
SetHandler application/x-httpd-php
</FILES>
Then I replaced my old static css calls with this:
<link rel="stylesheet" type="text/css" href="assets/path/to/your/css/css.css?your,filenames,sans_extensions,separated,by_commas" />
You can visit
http://www.yoursite.com/assets/path/to/your/css/css.css?your,filenames,sans_extensions,separated,by_commas and see what the output is. Saving the text file gave me a 61KB filesize. I checked with Firebug if I was getting any compression benefits out of this, and I was - the css link is reported to have a size of 9.8KB (See attached image).
Can anyone improve this further or plug any security holes it may have? Or maybe find a way to convert this to a snippet, or give this a sort of caching feature.. Anyone got an idea how much load this code going to hit the CPU?
UPDATE: This is odd. Sometimes it's compressed, sometimes it's not. I've read in some blog posts that the decision to compress files is dependent on how busy the web server is.. Wonder if this is the case.
[ed. note: diatomin last edited this post 13 years, 8 months ago.]