帝国cms PHP缓存网页代码 加速访问

化后的缓存文件。

适用于任何php网站。

从根本解决你网站速度问题!

<?php

/******************
require(ECMS_PATH . 'cache/content.php');
*******************************************/
//缓存存放目录
define('CACHE_ROOT', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'cacheFile'); 
//缓存文件后缀
define('CACHE_FIX','.php');

date_default_timezone_set("Asia/Shanghai");

// 获取当前URL路径信息
$query_string = $_SERVER['QUERY_STRING'];

// 解析路径,获取顶级栏目
$url_path = '';
if (!empty($query_string)) {
    // 解析查询字符串,去除参数部分
    $query_parts = explode('&', $query_string);
    // 假设第一个参数是路径信息(根据ThinkPHP的路由规则)
    $first_param = $query_parts[0];
    if (strpos($first_param, '/') !== false) {
        $url_path = $first_param;
    } else {
        // 如果不是路径形式,可能是参数,则根据实际情况处理
        $url_path = $query_string;
    }
}

// 提取顶级栏目
$top_category = 'index'; // 默认为首页
if (!empty($url_path)) {
    // 移除可能的文件扩展名
    $url_path = preg_replace('/\.(html|htm|php)$/i', '', $url_path);
    
    // 按斜杠分割路径
    $path_parts = explode('/', $url_path);
    
    // 获取第一个非空的部分作为顶级栏目
    foreach ($path_parts as $part) {
        if (!empty($part)) {
            $top_category = $part;
            break;
        }
    }
    
    // 如果顶级栏目包含特殊字符或过长,使用md5简化
    if (strlen($top_category) > 50 || preg_match('/[^\w\-\.]/', $top_category)) {
        $top_category = md5($top_category);
    }
}

// 生成缓存文件名和路径
$cache_key = md5($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
$CacheName = $cache_key . CACHE_FIX;

// 计算子目录(md5倒数第一个字符)
$sub_dir = substr($cache_key, -1, 1);

// 构建完整的缓存目录和路径
$CacheDir = CACHE_ROOT . DIRECTORY_SEPARATOR . $top_category . DIRECTORY_SEPARATOR . $sub_dir;
$CacheUrl = $CacheDir . DIRECTORY_SEPARATOR . $CacheName;

// 检查缓存是否存在
if(file_exists($CacheUrl)){ 
    echo str_replace("{time181}",date("Y-m-d h:i:m",time()-1440),gzuncompress(file_get_contents($CacheUrl)));
    exit; 
}

// 创建缓存目录(如果需要)
if(!file_exists($CacheDir)){ 
    // 创建缓存根目录
    if(!file_exists(CACHE_ROOT)){ 
        mkdir(CACHE_ROOT,0777, true); 
        chmod(CACHE_ROOT,0777); 
    }
    
    // 创建顶级栏目目录
    $top_category_dir = CACHE_ROOT . DIRECTORY_SEPARATOR . $top_category;
    if(!file_exists($top_category_dir)) {
        mkdir($top_category_dir,0777, true); 
        chmod($top_category_dir,0777); 
    }
    
    // 创建子目录
    mkdir($CacheDir,0777, true); 
    chmod($CacheDir,0777); 
}

// 缓存输出函数
function AutoCache($contents){ 
    global $CacheUrl; 
    $fp = fopen($CacheUrl,'wb'); 
    $contents = "<!--缓存插件作者QQ:181021679  ".(date("Y-m-d H:i:s", time()))."-->\r\n" . $contents;
    fwrite($fp, gzcompress($contents)); 
    fclose($fp); 
    chmod($CacheUrl,0777); 
    return str_replace("{time181}", date("Y-m-d h:i:m",time()-1440), $contents);
}

ob_start('AutoCache');
clearstatcache();

更新后的版本。

<?php
/******************
require(ECMS_PATH . '/cache.php');
*******************************************/
if (1 == 1) {
    // 缓存存放目录
    define('CACHE_ROOT', dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'cacheFile');
    // 缓存文件后缀
    define('CACHE_FIX', '.php');

    date_default_timezone_set("Asia/Shanghai");

    // 创建缓存根目录(如果不存在)
    if (!file_exists(CACHE_ROOT)) {
        if (!mkdir(CACHE_ROOT, 0755, true)) {
            error_log('无法创建缓存目录: ' . CACHE_ROOT);
        } else {
            chmod(CACHE_ROOT, 0755);
        }
    }

    /**
     * 页面类型识别(用于分目录存储)
     */
    function getPageType() {
        $requestUri = $_SERVER['REQUEST_URI'];
        $scriptName = $_SERVER['SCRIPT_NAME'];

        if (strpos($scriptName, 'index.php') !== false || $requestUri === '/' || $requestUri === '/index.php') {
            return 'index';
        }
        if (strpos($requestUri, '/singer/') !== false) {
            return 'singer';
        }
        if (strpos($requestUri, '/jieshuo/') !== false) {
            return 'jieshuo';
        }
        if (strpos($scriptName, 'content.php') !== false || strpos($requestUri, '/lyrics/') !== false) {
            return 'content';
        }
        if (strpos($scriptName, 'list.php') !== false || strpos($requestUri, '/list/') !== false) {
            return 'list';
        }
        if (strpos($scriptName, 'search.php') !== false) {
            return 'search';
        }
        return 'other';
    }

    /**
     * 获取缓存文件路径
     */
    function getCacheFileName() {
        $pageType = getPageType();
        $cacheKey = md5($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']) . CACHE_FIX;
        $cacheDir = CACHE_ROOT . DIRECTORY_SEPARATOR . $pageType . DIRECTORY_SEPARATOR . substr($cacheKey, 0, 1);
        $cacheFile = $cacheDir . DIRECTORY_SEPARATOR . $cacheKey;
        return [
            'dir' => $cacheDir,
            'file' => $cacheFile,
            'type' => $pageType
        ];
    }

    /**
     * 读取缓存内容(直接解压,无元数据)
     */
    function readCache($cacheFile) {
        if (!file_exists($cacheFile)) {
            return false;
        }
        $compressed = file_get_contents($cacheFile);
        if ($compressed === false) return false;
        $decompressed = @gzuncompress($compressed);
        if ($decompressed === false) return false;
        return $decompressed;
    }

    /**
     * 写入缓存内容
     * 在内容最前面添加缓存生成时间的HTML注释
     */
    function writeCache($cacheFile, $content) {
        $dir = dirname($cacheFile);
        if (!file_exists($dir)) {
            mkdir($dir, 0755, true);
        }
        // 添加头部注释,记录缓存生成时间
        $header = '<!-- 缓存生成时间:' . date('Y-m-d H:i:s') . ' -->' . "\n";
        $compressed = gzcompress($header . $content);
        return file_put_contents($cacheFile, $compressed) !== false;
    }

    /**
     * 生成伪发布时间(近三天内,同页面同一天不变)
     */
    function getTime181Value() {
        $today = date('Y-m-d');
        $url = $_SERVER['REQUEST_URI'];
        $seed = $url . $today;
        $hash = md5($seed);
        $hex = substr($hash, 0, 8);
        $offset = hexdec($hex) % 172800; // 0~2天的秒数
        $base = strtotime($today . ' 00:00:00');
        $fakeTime = $base - $offset;
        return date('Y-m-d H:i:s', $fakeTime);
    }

    $cacheInfo = getCacheFileName();
    $CacheDir = $cacheInfo['dir'];
    $CacheUrl = $cacheInfo['file'];
    $pageType = $cacheInfo['type'];

    // 缓存命中:直接读取并输出,不做任何元数据更新
    if (http_response_code() === 200 && file_exists($CacheUrl)) {
        $content = readCache($CacheUrl);
        if ($content !== false) {
            // 替换占位符后输出(注意:缓存中已包含头部注释)
            echo str_replace("{time181}", getTime181Value(), $content);
            exit;
        }
    }

    // 创建缓存子目录(若不存在)
    if (!file_exists($CacheDir)) {
        if (!mkdir($CacheDir, 0755, true)) {
            error_log('无法创建缓存子目录: ' . $CacheDir);
        } else {
            chmod($CacheDir, 0755);
        }
    }

    /**
     * 自动缓存回调:替换占位符并写入缓存(写入时会自动添加头部注释)
     */
    function AutoCache($contents) {
        global $CacheUrl;

        // 替换占位符为伪发布时间
        $replaced = str_replace("{time181}", getTime181Value(), $contents);

        // 仅当状态码为200且内容非空时缓存
        if (http_response_code() === 200 && !empty($replaced)) {
            writeCache($CacheUrl, $replaced);
        }

        return $replaced;
    }

    ob_start('AutoCache');
    clearstatcache();
}
?>

 

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容