标签归档:404

写的一个简单的PHP缓存类

前几天写过一篇巧用404.php解决Wordpress耗资源的问题,给Wordpress加个缓存功能(http://www.miaoqiyuan.cn/p/wordpress-haoziyuan-wordpress-cache)中提到了PHP缓存的方法,总感觉不是很方便,现在我又写了一个新的。

< ?php
	class cache404{
		public $K,$P;
		public function __construct($URI,$P='blog',$Par='./cache/'){
			$this->U = $URI;
			$this->K = md5($URI);
			$this->P = $P;
			$this->Par = $Par;
			$this->E = '.tmp_miaoqiyuan';
			$this->F = $this->Par . $this->P . '/' . $this->K . $this->E;
		}
		public function getCache(){
			if(!!($fp=@fopen($this->F,'r'))){
				$html=fread($fp,102400);
			}else{
				$html=file_get_contents($this->U);
				$this->addIndex();
				$fp=fopen($this->F,'w');
				fwrite($fp,$html);
			}
			fclose($fp);
			return $html;
		}
		public function noCache(){
			$html=file_get_contents($this->U);
			$fp=fopen($this->F,'w');
			fwrite($fp,$html);
			fclose($fp);
			return $html;
		}
		public function flushCache(){
			unlink($this->F);
		}
		public function addIndex(){
			$fpidx=fopen($this->Par . $this->P . '.rtf','a');
			fwrite($fpidx,$this->K . '	' .$this->U);
			fclose($fpidx);
		}
}
?>

用的时候很简单

	require_once('./inc/404cache.php');
	$Cache=new cache404($URI,$Path);
	#echo $Cache->noCache();
	echo $Cache->getCache();
< ?php
	require_once('./inc/404cache.php');
	$q=explode("/",$URI=substr(($qs = strtolower($_SERVER['QUERY_STRING'])),strpos($qs, ':80')+4));
	$URI="/".$URI;
	switch($q[0]){
		case 'test':
			#/test	->	/seo_test/test.asp
			if(preg_match('/^\/test(\/)?$/',$URI)){
				$URI='http:'.'//'.$_SERVER['SERVER_NAME'].'/seo_test/test.asp';
			}

			#/test/[a-z]\.html	->	/seo_test/test.asp?key=$1
			else if(preg_match('/^\/test\/([a-z])\.html$/',$URI,$Match)){
				$URI='http:'.'//'.$_SERVER['SERVER_NAME'].'/seo_test/test.asp?key='.$Match[1];
			}else{
				$URI='http:'.'//'.$_SERVER['SERVER_NAME'].'/seo_test/test.asp';
			}
			$Path='test';
		default:
			$URI='http:'.'//'.$_SERVER['SERVER_NAME'].'/index.php'.$URI;
			$Path='blog';
	}
	$Cache=new cache404($URI,$Path);
	#echo $Cache->getCache();
	echo $Cache->noCache();
?>