...
PHP

php文件缓存类,简单的文件缓存

闲来无事,整个文件缓存吧~

原理:
1、就是对当前访问的url做md5
2、然后通过md5的文件名去找缓存目录中是否有该文件
3、取文件第一行,(缓存文件第一行是缓存的时间戳 )比对时间戳是否过期
4、没有过期就直接输出文件内容,过期了访问真实地址,做下次缓存。

记录一下:

<?php
/**
 * 文件缓存
 */
// 跟目录
define('ROOT', './');
define('CACHE_PATH', './cache/');
class cache
{
    // 文件过期时间
    private static $expires = 300;
    // 文件地址
    private $file_path = null;
    public function __construct()
    {
        $url = $this->curPageURL();
        // 判断当前url是否有缓存
        $file_name = md5($url).".php";
        $this->file_path = CACHE_PATH . $file_name;
        // 检查缓存文件是否存在
        if(file_exists($this->file_path)){
            // 存在就检查缓存是否被过期了
            $f = fopen($this->file_path,'r');
            // 取文件的第一行
            $line = fgets($f,4096);
            // 检查这行是不是标志行
            $timer = preg_replace("/^<\!--(\d{10})-->\n$/","$1",$line);
            if($timer && $timer > time()){
                // 输出缓存文件
                $content = fread($f,filesize($this->file_path));
                fclose($f);
                echo $content;
                exit;
            }
            if($f) fclose($f);
        } 
        // 否则就开始缓存
        ob_start();
    }

    public function flush()
    {
        $content = ob_get_contents();
        // 写入文件
        $f = fopen($this->file_path,'w+');
        $timer = time() + self::$expires;
        $content = "<!--$timer-->\n" . $content;
        fwrite($f,$content);
        fclose($f);
        ob_end_flush();
    }

    // 获取完整URL
    private function curPageURL()
    {
        $pageURL = 'http';
        if ($_SERVER["HTTPS"] == "on") {
            $pageURL .= "s";
        }
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }
}

使用:a.php

<?php
$cache = new cache();
?>
<html>
...
</html>
<?php
$cache->flush();
?>
mysql时间日期查询,昨天、本周、本月、本季度、本年 时间日期条件sql语句 Android Java ASE加解密与PHP AES加解密
biu biu biu
Android Java ASE加解密与PHP AES加解密 Nginx反向代理是什么,及反向代理的基本配置 php文件缓存类,简单的文件缓存 js生成日期,昨天、前天、今天、明天、一周后日期生成 mysql时间日期查询,昨天、本周、本月、本季度、本年 时间日期条件sql语句