有两种方式与直PHP来做到这一点
页眉计算策略
$cachetime = 60 * 60 * 24 * 7; // 1 Week
header(‘Expires: ‘.gmdate(‘D, d M Y H:i:s’, time()+$expires).’GMT’);
或者通过缓存完整的文件(包括从动态内容/内容)在你的文件系统(可用于网站的缓存部分)
<?php
$cachefile = "cache/".$reqfilename.".html"; #change $reqfilename to $_SERVER['PHP_SELF'] if you are using in headers, footers, menus files
$cachetime = 60 * 60 * 24 * 7; // 1 Week
// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile))) {
include($cachefile);
exit;
}
ob_start(); // start the output buffer
?>
.. Your usual PHP script and HTML here ...
<?php
// open the cache file for writing
$fp = fopen($cachefile, 'w');
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());
// close the file
fclose($fp);
// Send the output to the browser
ob_end_flush();
?>
什么你也可以做的是通过使用头或更新缓存信息您的htaccess缓存用户计算机上的文件。 htaccess的实现可能会有所不同,具体取决于托管服务器上安装的模块。我使用:
# Add Expiration
ExpiresActive On
ExpiresDefault "access plus 1 week"
ExpiresByType text/html "access plus 1 day"
ExpiresByType text/php "access plus 1 day"
ExpiresByType image/gif "access plus 1 week"
ExpiresByType image/jpeg "access plus 1 week"
ExpiresByType image/png "access plus 1 week"
ExpiresByType text/css "access plus 1 week"
ExpiresByType text/javascript "access plus 1 week"
ExpiresByType application/x-javascript "access plus 1 week"
ExpiresByType image/x-icon "access plus 1 week"
ExpiresByType image/ico "access plus 1 week"
ExpiresByType text/xml "access plus 1 day"
是啊!那是我的想法。有没有最佳实践指南? – Manz
@Manz,好吧,这很简单,我不确定最佳实践指南是什么意思......你有一个HTML页面(如果你只有静态内容,你甚至不需要制作.php)占位符。你缓存这个页面,然后当你需要显示它时,你从缓存中获取它,并用一个简单的'str_replace()'替换占位符... – rid