---
title: "PHP 数据缓存"
author: "jaredsun"
date: "2010-12-09T15:23:00Z"
tags: []
categories: ["编程语言"]
slug: "php"
draft: false
lastmod: "2010-12-09T15:23:00Z"
id: 837633
url: "https://jaredsun.iteye.com/blog/837633"
---

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

```php

 //读取文件内容
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,然后，一个简单的缓存可以这样来处理**

```php

       $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--)