ITeye博客

PHP 数据缓存

jaredsun · 2010-12-09 15:23 · PHP+Mysql · 编程语言 · Markdown

今天有个以前smarty开发的网站,现在做个seo后台处理,考虑到访问量的原因,决定用缓存处理,最开始一直认为要用smarty的模板缓存缓存机制。最后讨论下发现。这是个数据缓存。脑袋也清晰许多。 首先需要两个读取和写入函数,uch里面有现成的


 //读取文件内容
function swritefile($filename, $writetext, $openmod='w')
 {
    if(@$fp = fopen($filename, $openmod))
   {
        flock($fp, 2);
        fwrite($fp, $writetext);
        fclose($fp);
        return true;
    } 
     else 
    {
        return false;
    }
}
//获取文件内容
function sreadfile($filename) 
{
    $content = '';
    if(function_exists('file_get_contents'))
   {
        @$content = file_get_contents($filename);
    } 
    else 
    {
        if(@$fp = fopen($filename, 'r'))
        {
            @$content = fread($fp, filesize($filename));
            @fclose($fp);
         }
    }
    return $content;
}

2,然后,一个简单的缓存可以这样来处理


       $data_path='../data/seo_data/';   //缓存路径
	if(!file_exists($data_path))
	{
		mkdir($data_path);
	}
	$data_file = $data_path.$id.'.php'; //缓存文件名称,$id可以设置成字符串数字等
	$cache_time=filemtime($data_file);
	if(!file_exists($data_file) || (time()-$cache_time)>3600)
	{
        /*$list
        这里显示需要缓存的数据(从数据库里面读出来等)
        */
        swritefile($data_file, serialize($list)); //序列化读入文件
	}
	else
	{
		$list = unserialize(sreadfile($data_file));//没过期且有缓存文件存在时,读缓存文件。
	}
	$list;//缓存过的值


(--end--)

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。