Reputation: 3063
So I have been using Minify to compress my JS and CSS which had all been going nicely until I needed to compress some dynamic php stylesheets.
I tried to use htaccess to fool it into thinking it was a css file, but I then realised it uses absolute file paths which would not be effected by mod_rewrite
Anyways whenever I point it at a php file, it always returns '400 Bad Request'. Any idea on how to solve this other than writing my own compression script?
Upvotes: 4
Views: 2596
Reputation: 22947
I find the best way to deal with minifying and compressing stylesheets is to do it yourself. Check out this code:
<?php
header("Content-Type: text/css");
header("Last-Modified: ".gmdate('D, d M Y H:i:s', filemtime($_SERVER['DOCUMENT_ROOT'].$_SERVER['PHP_SELF']))." GMT");
header("Expires: ".gmdate('D, d M Y H:i:s', (filemtime($_SERVER['DOCUMENT_ROOT'].$_SERVER['PHP_SELF']) + 691200))." GMT");
//This GZIPs the CSS for transmission to the user
//making file size smaller and transfer rate quicker
ob_start("ob_gzhandler");
ob_start("compress");
//Function for compressing the CSS as tightly as possible
function compress($buffer) {
//Remove CSS comments
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
//Remove tabs, spaces, newlines, etc.
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
return $buffer;
}
//Main style
require_once($_SERVER['DOCUMENT_ROOT']."/templates/style/style.css");
//Other style
if($php_variable) {
require_once($_SERVER['DOCUMENT_ROOT']."/templates/style/other.css");
}
ob_end_flush();
ob_end_flush();
?>
There's a lot of things going on here, so let me explain.
Headers
Last-Modified
and Expires
header for cache control (Setting at slightly over a week, you can change this).Minify and GZIP
ob_start
, we tell it to GZIP this file as well as run a custom function compress
.compress
removes all CSS comments and white space when sending to to the browser. This means you can keep all your comments and spacing the way you like it in your source files for easier editing, but only send the bare minimum to the browser.Style
require
to import the stylesheets. Do this for as many stylesheets as you'd like; They'll all get delivered in a single HTTP request to the user.Using Your New File
You'll call on the file just as you would a normal CSS file.
<style type="text/css" src="/path/to/css-script.php"></style>
Conclusion
Using this method, you're doing several awesome things.
@import
statements...which in itself is awesome.You can use this same method for JavaScript as well, though the compress
function above is strictly for CSS so I would omit it.
Use this technique in combination with this cache control technique, and you've built yourself an awesome CSS/JS handler: How to force browser to reload cached CSS/JS files?
Upvotes: 8