[英]cache headers for dynamic css (generated via PHP)
我的CSS文件实际上是一个PHP文件,它与内容类型text/css
以便我可以在该文件中使用PHP变量。 style.php
看起来像这样:
<?php
header('Content-Type: text/css');
$bgColor = '#000';
?>
body { background:<?php print $bgColor; ?>; }
它按预期工作,但如果浏览器缓存动态创建的css文件,我有点担心。
在查看firebug中的请求时,在我看来浏览器每次重新加载页面时style.php
重新加载style.php
。
我已经尝试添加这些缓存标头:
header('Cache-control: must-revalidate');
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 60 * 60 * 24) . ' GMT');
但没有运气。 每次加载页面时仍会加载该文件。 为了强制浏览器在一定时间内缓存文件,有哪些适当的标题?
如果您希望浏览器缓存文件,则应将Cache-control标头设置为public:
header('Cache-control: public');
必须重新验证意味着浏览器将检查文件是否已更新,这将调用您的PHP脚本。
此代码可以解决您的问题。
它检查“上次修改”变量并为文件分配eTag。 如果修改了eTag(或修改了文件),则会显示该文件。 否则,会出现304 HTTP错误,指出该页面未被修改。
eTag实际上就是你要找的东西。
码:
<?php
// Custom variables
$variables = array('#CCC','#800'); // from db
// CSS Content
header('Content-type: text/css');
// Last Modified
$lastModified = filemtime(__FILE__);
// Get a unique hash of this file (etag)
$etagFile = md5_file(__FILE__);
// Get the HTTP_IF_MODIFIED_SINCE header if set
$ifModifiedSince = (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false);
// Get the HTTP_IF_NONE_MATCH header if set (etag: unique file hash)
$etagHeader = (isset($_SERVER['HTTP_IF_NONE_MATCH']) ? trim($_SERVER['HTTP_IF_NONE_MATCH']) : false);
// Set last-modified header
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $lastModified)." GMT");
// Set etag-header
header("Etag: $etagFile");
// Make sure caching is turned on
header('Cache-Control: public');
// Check if page has changed. If not, send 304 and exit
if(@strtotime($ifModifiedSince) == $lastModified || $etagHeader == $etagFile){
header("HTTP/1.1 304 Not Modified");
exit;
}
?>
body {background: <?php echo $variables[0]; ?>;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.