以下脚本将:
我的问题是第2步:返回文件的服务器缓存版本。从我创建原始文件的位置可以看出,我还发送了一些标题来指示返回文件的类型,并允许客户端缓存文件。返回文件的服务器缓存版本时,如何发送相同的标头?
关闭主题并且与此问题无关,但是对于我如何命名缓存文件的任何评论都将不胜感激。 $cachefile = $root.'/ayb_cache/'.preg_replace("/[^A-Za-z0-9 ]/", '', basename($_SERVER['REQUEST_URI']));
<?php
date_default_timezone_set('UTC');
$root=dirname(dirname(dirname(dirname(__FILE__))));
$filetime=filemtime(__FILE__);
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $filetime))
{
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $filetime).' GMT', true, 304);
}
else
{
//Not yet cached on client
$cachefile = $root.'/ayb_cache/'.preg_replace("/[^A-Za-z0-9 ]/", '', basename($_SERVER['REQUEST_URI']));
$cachetime=60*60*24*14;
if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile)))
{
// Serve from the cache if it is younger than $cachetime
include($cachefile);
//echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))." -->";
echo "/* Cached ".date('jS F Y H:i', filemtime($cachefile))." */";
}
else
{
//create new file
ob_start();
header( 'Content-type: text/javascript' ); //tell the browser we're returning JS
header('Pragma: public');
header('Cache-Control: public, maxage='.$cachetime);
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$cachetime) . ' GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime(__FILE__)).' GMT', true, 200);
echo('alert("My Javascript");');
$fp = fopen($cachefile, 'w'); // open the cache file for writing
fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file
fclose($fp);
ob_end_flush(); // Send the output to the browser
}
}
?>
答案 0 :(得分:1)
在下面的代码中包含header();
语句之前的include($cachefile)
次调用。
if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile)))
{
// Serve from the cache if it is younger than $cachetime
include($cachefile);
//echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))." -->";
echo "/* Cached ".date('jS F Y H:i', filemtime($cachefile))." */";
}