7个超级实用的PHP代码片段
前端之家收集整理的这篇文章主要介绍了
7个超级实用的PHP代码片段,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
1、超级简单的页面缓存
如果你的工程项目不是基于 CMS 系统或框架,打造一个简单的缓存系统将会非常实在。下面的代码很简单,但是对小网站而言能切切实实解决问题。
<div class="codetitle"><a style="CURSOR: pointer" data="96651" class="copybut" id="copybut96651" onclick="doCopy('code96651')"> 代码如下:
<div class="codebody" id="code96651">
<?
PHP // define the path and name of cached file
$cachefile = 'cached-files/'.date('M-d-Y').'.
PHP';
// define how long we want to keep the file in seconds. I set mine to 5 hours.
$cachetime = 18000;
// Check if the cached file is still fresh. If it is,serve it up and exit.
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
include($cachefile);
exit;
}
// if there is either no file OR the file to too old,render the page and capture the HTML.
ob_start();
?>
output all your html here.
<?
PHP // We're done! Save the cached content to a file
$fp = fopen($cachefile,'w');
fwrite($fp,ob_get_contents());
fclose($fp);
// finally send browser output
ob_end_flush();
?>