发送标题下面的脚本将:与服务器缓存文件
返回一个304未修改头,如果该文件的客户端缓存的版本是最新的。
如果不是,那么它将返回该文件的服务器缓存版本(如果它是最新的)。
如果不是,它将创建文件,在服务器端缓存中存储副本,然后返回文件。
我的问题是第2步:返回一个服务器缓存的文件版本。正如我在创建原始文件的位置所看到的,我还会发送一些标题来指示返回的文件的类型,并允许客户端缓存文件。如何在返回文件的服务器缓存版本时发送相同的头文件?
偏离主题,不涉及这个问题,但任何评论我如何命名缓存的文件将不胜感激。 $cachefile = $root.'/ayb_cache/'.preg_replace("/[^A-Za-z0-9 ]/", '', basename($_SERVER['REQUEST_URI']));
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 "";
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
}
}
?>