如何在PHP中缓存网页? [英] How do I cache a web page in PHP?
问题描述
如何在php中缓存网页,以便如果尚未更新页面,则查看者应获取缓存的副本?
how do I cache a web page in php so that if a page has not been updated viewers should get a cached copy?
感谢您的帮助。
PS:我是php的初学者。
Thanks for your help. PS: I am beginner in php.
推荐答案
您实际上可以保存页面的输出,然后结束脚本,然后在脚本开始处加载缓存。
You can actually save the output of the page before you end the script, then load the cache at the start of the script.
示例代码:
<?php
$cachefile = 'cache/'.basename($_SERVER['PHP_SELF']).'.cache'; // e.g. cache/index.php.cache
$cachetime = 3600; // time to cache in seconds
if(file_exists($cachefile) && time()-$cachetime <= filemtime($cachefile)){
$c = @file_get_contents($cf);
echo $c;
exit;
}else{
unlink($cachefile);
}
ob_start();
// all the coding goes here
$c = ob_get_contents();
file_put_contents($cachefile);
?>
如果您有很多需要此缓存的页面,则可以执行以下操作:
If you have a lot of pages needing this caching you can do this:
在 cachestart.php
中:
<?php
$cachefile = 'cache/'.basename($_SERVER['PHP_SELF']).'.cache'; // e.g. cache/index.php.cache
$cachetime = 3600; // time to cache in seconds
if(file_exists($cachefile) && time()-$cachetime <= filemtime($cachefile)){
$c = @file_get_contents($cf);
echo $c;
exit;
}else{
unlink($cachefile);
}
ob_start();
?>
在 cacheend.php
中:
<?php
$c = ob_get_contents();
file_put_contents($cachefile);
?>
然后只需添加
include('cachestart.php');
在脚本开始时。并添加
include('cacheend.php');
在脚本末尾。记住要有一个名为 cache 的文件夹,并允许PHP访问它。
at the end of your scripts. Remember to have a folder named cache and allow PHP to access it.
另外请记住,如果要进行全页缓存,您的页面不应具有SESSION特定的显示(例如,显示成员的栏或其他内容),因为它们也将被缓存。查看特定缓存(变量或页面的一部分)的框架。
Also do remember that if you're doing a full page cache, your page should not have SESSION specific display (e.g. display members' bar or what) because they will be cached as well. Look at a framework for specific-caching (variable or part of the page).
这篇关于如何在PHP中缓存网页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!