文件缓存函数

function set_cache($key,$value,$timeout=0){
	$cache_path = _SITE_CACHE."_cache_".$key;
	//cache content
	$cache_content = base64_encode(serialize($value));
	
	//cache file
	$cache_file_x = $cache_path."x";
	$cache_file_y = $cache_path."y";
	
	//加入缓存时间
	if( $timeout > 0 ) $cache_content.= "\n".$timeout;
	
	//cache time
	if( file_exists($cache_file_x) )	$cache_x_time = filemtime($cache_file_x);
	if( file_exists($cache_file_y) )	$cache_y_time = filemtime($cache_file_y);
	//write cache
	if( !file_exists($cache_file_x) )	file_put_contents($cache_file_x,$cache_content,LOCK_EX);
	if( !file_exists($cache_file_y) )	file_put_contents($cache_file_y,$cache_content,LOCK_EX);	
	
	//update cache
	if( $cache_x_time>$cache_y_time ){
		#echo "write y [".$cache_file_y."]<br/>\n";
		file_put_contents($cache_file_y,$cache_content,LOCK_EX);
	}
	else{
		#echo "write x [".$cache_file_x."]<br/>\n";
		file_put_contents($cache_file_x,$cache_content,LOCK_EX);
	}
}
function get_cache($key,$model=0){
	//cache path
	$cache_path = _SITE_CACHE."_cache_".$key;
	
	//cache file
	$cache_file_x = $cache_path."x";
	$cache_file_y = $cache_path."y";
	if( !file_exists($cache_file_x) && !file_exists($cache_file_y) ) return false;
	
	//cache time
	$cache_x_time = filemtime($cache_file_x);
	$cache_y_time = filemtime($cache_file_y);
	//	
	if( $cache_x_time>$cache_y_time ){
		$cache_file  = $cache_file_x;
		$update_time = $cache_x_time;
	}
	else{
		$cache_file = $cache_file_y;
		$update_time = $cache_y_time;
	}
	#echo "use [".$cache_file."]<br/>\n";
	$cache_arrays = explode("\n",file_get_contents($cache_file));
	
	if( count($cache_arrays) == 2 && 0 === $model && time()-$update_time > $cache_arrays[1] ){
		 return false;
	}
	else return unserialize(base64_decode($cache_arrays[0]));
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值