我縫合css文件以提高性能。縫合css文件並縮小onthefly
現在我想包括一個minify函數如下。我怎樣才能合併這個?
function minify($css) {
$css = preg_replace('#\s+#', ' ', $css);
$css = preg_replace('#/\*.*?\*/#s', '', $css);
$css = str_replace('; ', ';', $css);
$css = str_replace(': ', ':', $css);
$css = str_replace(' {', '{', $css);
$css = str_replace('{ ', '{', $css);
$css = str_replace(', ', ',', $css);
$css = str_replace('} ', '}', $css);
$css = str_replace(';}', '}', $css);
return trim($css);
}
代碼以進行拼接:
<?php
$filename = $_GET['files'];
// validate that $filename is set, contains only legal characters
// and does not contain multiple dots (potential sign of trouble)
if (!$filename ||
!preg_match('/^([\.\-\_a-z0-9]*)$/i', $filename) ||
preg_match('/([\.]{2,})/', $filename))
exit();
// we're sending CSS back to the browser
header('Content-Type: text/css');
$files = explode('-', $filename, 15);
// we're also writing CSS to a subdirectory "cache"
// the filename will be the hyphen-delimited value
// of $filename
$cachefile = @fopen('cache/'. $filename, 'w');
// loop through, read each file, and stitch them together
foreach ($files AS $file) {
$fcontents = null;
if ($cssfile = fopen($file, 'r')) {
$fcontents = fread($cssfile, filesize($file)) ."\n";
fclose($cssfile);
}
// if we read something, write it and send it to browser
if ($fcontents) {
fwrite($cachefile, $fcontents, strlen($fcontents));
echo $fcontents;
}
}
// all done
fclose($cachefile);
?>
順便說一句,你沒有正確地逃避文件名。列入黑名單是一個壞主意,您應該檢查您獲得的真實路徑是否指向緩存目錄中的某個位置。 http://cwe.mitre.org/top25/#CWE-22 – Clueless
你能幫我嗎?'因爲我不明白這一點。 – mark