PHP缓存写入和读取缓存文件

180it 2021-06-19 PM 1423℃ 0条
调用:  $cacheData = serialize(数据);//序列化
        $this->cacheWrite($cacheData, '缓存名称');

    

/**
     * 写入缓存
     */
    function cacheWrite ($cacheData, $cacheName) {
        $cachefile = EMLOG_ROOT . '/content/cache/' . $cacheName . '.php';
        $cacheData = "<?php exit;//" . $cacheData;
        @ $fp = fopen($cachefile, 'wb') OR emMsg('读取缓存失败。如果您使用的是Unix/Linux主机,请修改缓存目录 (content/cache) 下所有文件的权限为777。如果您使用的是Windows主机,请联系管理员,将该目录下所有文件设为可写');
        @ $fw = fwrite($fp, $cacheData) OR emMsg('写入缓存失败,缓存目录 (content/cache) 不可写');
        $this->{$cacheName.'_cache'} = null;
        fclose($fp);
    }

    /**
     * 读取缓存文件
     */
    function readCache($cacheName) {
        if ($this->{$cacheName.'_cache'} != null) {
            return $this->{$cacheName.'_cache'};
        } else {
            $cachefile = EMLOG_ROOT . '/content/cache/' . $cacheName . '.php';
            // 如果缓存文件不存在则自动生成缓存文件
            if (!is_file($cachefile) || filesize($cachefile) <= 0) {
                if (method_exists($this, 'mc_' . $cacheName)) {
                    call_user_func(array($this, 'mc_' . $cacheName));
                }
            }
            if ($fp = fopen($cachefile, 'r')) {
                $data = fread($fp, filesize($cachefile));
                fclose($fp);
                clearstatcache();
                $this->{$cacheName.'_cache'} = unserialize(str_replace("<?php exit;//", '', $data));
                return $this->{$cacheName.'_cache'};
            }
        }
    }
支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

PHP缓存写入和读取缓存文件