0

我有一个名为 main.css.php 的 php 文件,它收集多个 css 文件并将它们输出为一个大 css 文件。它收集的 css 文件数量范围为 1-10。代码是这样的:

header('Content-type: text/css');
header('Cache-Control: max-age=31536000');
ob_start("compress");
function compress($buffer) {
    /* remove comments */
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
    /* remove tabs, spaces, newlines, etc. */
    $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
    return $buffer;
}

// include css files
foreach ($css_files as $path) {
    if (file_exists($path)) {
        include_once($path);
    }
}
ob_end_flush();

所以我对那部分进行了排序,但现在我不确定如何缓存它,如果任何原始 css 文件发生更改,我可以更新缓存。正如this answer中所建议的,我将执行以下操作:

$cache = "";
foreach ($css_files as $path) {
    $cache.= filemtime($path);
}
...
echo "<link rel='stylesheet' href='/css/base.{$cache}.css'>";

但是我不能使用这个 apache 重写规则:

RewriteEngine on
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]

因为我不确定 $cache 将包含多长时间,因为它将包含多个 unix 时间戳。

概括

我需要将多个 css 文件组合成一个 php 文件,该文件使用 css 标头发送到浏览器。然后,我需要正确缓存此文件,但如果任何原始 css 文件发生更改,我可以通过一种方式更新缓存。

任何关于我正在做的事情的建议、建议或更好的方法将不胜感激。

4

2 回答 2

1

您应该对$cache变量进行哈希处理并在文件名中使用它。它会是这样的:

<?php

$cache = "";
foreach ($css_files as $path) {
    $cache .= filemtime($path);
}

$cache = md5($cache);

并且您的重写规则将使用哈希函数的长度;在这种情况下,我们使用md5,它有 32 个字符长:

RewriteEngine on
RewriteRule ^(.*)\.[\d]{32}\.(css|js)$ $1.$2 [L]

希望有帮助

于 2014-09-11T04:29:29.497 回答
1

为什么不将缓存信息存储在磁盘上?这样您就不必担心 .htaccess。

$prevTimes = filegetcontents('/cache/css.txt')
if(array_sum($filetimes) != (int) $prevTimes){
  //recompile css
  //update csscacheinfo.txt with $newTimes
  //echo css file link for stylesheet using $newTimes.css as css file
} else {
  //echo css file link for stylesheet using $prevTimes.css as css file
}

仅供参考:存储/添加整数比连接和比较字符串更快。

于 2014-09-11T04:38:25.307 回答