PHP 网站优化之页面静态化

页面静态化是提高网站访问速度的一个很好的优化方法,可以提高网站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;
	}
?>


优化前:

优化后:


希望能帮助到需要的人,如有大神有更好的方法,欢迎交流,指教(qq:524277477,微信:13263412524),本人原创,若转载,请说明出处。谢谢
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值