I'm using this php code to cache css files into a middle own CMS.
<?php
ob_start("ob_gzhandler");
ob_start("compress");
header("Content-type: text/css; charset: UTF-8");
header("Cache-Control: must-revalidate");
$off = 3600;
$exp = "Expires: " . gmdate("D, d M Y H:i:s", time() + $off) . " GMT";
header($exp);
function compress($buffer) {
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer); // remove comments
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer); // remove tabs, spaces, newlines, etc.
return $buffer;
}
require_once('style1.css');
require_once('style2.css');
?>
The big limitation in this code is that I cannot pass an argument to my "compress" function. For example, if I have a css file into an other directory, the relative path of the images are not replaced.
Do you know a way to add a parameter when i call my compress function and use for example something like this?
$buffer = str_replace('url("', 'url("'.$directory, $buffer);
Any suggestions are really appreciated!
Edit -> the final solution
After @Jack suggestions I'm arrived to this source.
Usage: in the header of the html page add this line:
<link href="cacheCSS.php" rel="stylesheet" type="text/css" />
ob_start("ob_gzhandler");
class CWD {
private $path;
public function __construct($path=NULL){
if(!isset($path)) $path = '';
$this->setPath($path);
}
public function setPath($path){
$this->path = $path;
}
public function getPath() {
return $this->path;
}
}
$directory = new CWD();
$compress = function($buffer) use ($directory) {
$buffer = str_replace('url("', 'url("'.$directory->getPath(), $buffer);
$buffer = str_replace('url(\'', 'url(\''.$directory->getPath(), $buffer);
$buffer = preg_replace('#^\s*//.+$#m', "", $buffer);
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
return $buffer;
};
ob_start($compress);
header("Content-type: text/css; charset: UTF-8");
header("Cache-Control: must-revalidate");
$off = 0; # Set to a reaonable value later, say 3600 (1 hr);
$exp = "Expires: " . gmdate("D, d M Y H:i:s", time() + $off) . " GMT";
header($exp);
/* List of CSS files*/
$directory->setPath('path1/');
include('path1/style1.css');
ob_flush();
$directory->setPath('path2/');
include('path2/style2.css');
ob_flush();
$directory->setPath('path3/');
include('path3/style3.css');