页面静态化是提高网站访问速度的一个很好的优化方法,可以提高网站50%以上的访问速度,但是也有缺点,就是换的数据无法及时更新。
那页面静态化是如何实现的呢,就是把PHP生成的动态页面保存成静态的html文件,用户访问该静态页面。
直接上代码:
<?php
error_reporting(E_ALL);
// 定义缓存文件
define("CACHE_PATH", str_replace("\\", "/" ,dirname(__FILE__)).'/cache/');
display_cache();
// 数据库链接
//
sleep(2);
// 网站逻辑
//
//
ob_start('ob_gzip');
// 引入模板文件
include 'test_tpl.php';
$output = ob_get_contents();
write_cache($output, 10);
return $output;
ob_end_clean();
/**
* 写入缓存
* @param string $output [要缓存的页面内容]
* @param string $time [缓存时间,单位分钟]
* @return [type] [description]
*/
function write_cache($output='', $time=0)
{
$filepath = get_cache_name();
$expire = time() + ($time * 60);
if (!$fp = @fopen($filepath, 'wb')){
return false;
}
if (flock($fp, LOCK_EX))
{
fwrite($fp, $expire.'--TIME-->'.$output);
flock($fp, LOCK_UN);
}
fclose($fp);
@chmod($filepath, 0755);
}
/**
* 读取缓存
* @return [string] [输出缓存的静态页面]
*/
function display_cache()
{
$filepath = get_cache_name();
if(!@file_exists($filepath)){
return false;
}
// 打开文件
if(!$fp = fopen(CACHE_PATH.$file_name,'rb')){
return false;
}
flock($fp,LOCK_SH);
$cache = '';
if (filesize($filepath) > 0)
{
$cache = fread($fp, filesize($filepath));
}
flock($fp, LOCK_UN);
fclose($fp);
// 判断文件格式是否正确,是否包含过期时间
if ( ! preg_match("/(\d+--TIME-->)/", $cache, $tres))
{
return FALSE;
}
// 判断时间是否过期,过期则删除掉
if (time() >= trim(str_replace('--TIME-->', '', $tres['1'])))
{
@unlink($filepath);
return FALSE;
}
$cache = preg_replace("/(\d+--TIME-->)/", '', $cache);
ob_start('ob_gzip');
echo $cache;
ob_end_flush();
die();
}
/**
* 获取缓存的文件名
* @return [type] [description]
*/
public function get_cache_name()
{
// 将当前页面的全路径MD5加密后作为缓存的文件名
$url = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].urldecode($_SERVER["REQUEST_URI"]);
$file_name = md5($url.'key_123'); // 加密的时候增加一个密钥,可以起到部分的反爬效果
return CACHE_PATH.$file_name;
}
/**
* 压缩要传输的内容
* @return [type] [description]
*/
function ob_gzip($contents='')
{
if(extension_loaded("zlib") && strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')){
$contents = gzencode($contents, 9, FORCE_GZIP);
header ("Content-Encoding: gzip");
}
header ('Content-Length: ' . strlen($contents));
return $contents;
}
?>
优化前:
优化后: