Hongmu Notes
Home Program Notes Empire cms PHP caches web page code to speed up access
Program Notes Empire cms

Empire cms PHP caches web page code to speed up access

Empire cms PHP caches web page code to speed up access

The cached file.

Works with any php website.

Solve your website speed problem fundamentally!

<?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();

Updated version.

<?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();
}
?>

 

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

Empire CMS database statement & SQL statement format

Empire CMS database statement & SQL statement format Program Notes Empire cms

Introduction to Imperial CMS extended SQL program writing, basic examples of Imperial CMS database statements & SQL statement formats: Note: The following examples are based on placing PHP files in the system root directory. Example 1: Connect to MYSQL program. (a.php)<?php require('e/class/connect.php'); //Introduce database configuration files and public function files requ…
👁 353
Empire CMS obtains the system COOKIE variable function getcvar()

Empire CMS obtains the system COOKIE variable function getcvar() Program Notes Empire cms

Get the system COOKIE variable function syntax: getcvar($var,$ecms) Description: $var: is the variable name $ecms: 0 is to set the foreground COOKIE variable, 1 is to set the background COOKIE variable. This parameter can be omitted and defaults to 0. Usage example: getcvar('mlusername'), get the user name of the front-end login member getcvar('loginu...
👁 296
Empire CMS smart label call field collection

Empire CMS smart label call field collection Program Notes Empire cms

Collect and classify all fields that support smart tag calls into Empire CMS smart tags: [e:loop={column ID/topic ID, number of items displayed, operation type, only display pictures with titles, additional SQL conditions, display sorting}] Template code content [/e:loop] Calling time: <?=date('m-d',$bqr[newstime])?> <?=dat…
👁 3749

Recommended reading

Responsive garden landscaping design corporate website template 0491

Responsive garden landscaping design corporate website template 0491 Practical Collection Yiyou template

An eyoucms responsive website template for gardening and landscaping design companies. The design style is natural art, which can display landscape design works, greening projects, plant configurations and design concepts. It helps garden design companies show their strength online and attract high-end project customers. Template display Installation instructions Website backend: /login.php Account: admin Password: admin Related articles Yiyou CMS installation FAQ...
👁 64
Responsive accounting and tax firm website template 0492

Responsive accounting and tax firm website template 0492 Practical Collection Yiyou template

This set of eyoucms responsive templates is suitable for accounting and tax firms. The design style is professional and rigorous, and can display accounting services, tax agencies, successful cases and corporate strength. It helps financial and taxation service agencies display their brands online and attract corporate customers. Template display Installation instructions Website backend: /login.php Account: admin Password: admin Related articles Yiyou CMS installation FAQ summary Yiyou CMS (…
👁 33
Responsive Minimalist B&B Website Template 0493

Responsive Minimalist B&B Website Template 0493 Practical Collection Yiyou template

An eyoucms responsive website template for simple B&Bs. The design style is warm and simple, which can display the B&B environment, room facilities, travel services and online booking. It helps B&Bs attract tourists online and enhance brand awareness. Template display Installation instructions Website backend: /login.php Account: admin Password: admin Related articles Summary of common problems in Eyo CMS installation Eyo CMS (Eyo…
👁 36
Resource website typecho001 template

Resource website typecho001 template Program Notes Typecho

typecho001 template template please do not modify the folder name of this template. The folder name is: typecho001 1.4 Fix the js output problem on the article page 1.3 Fix the error prompt when the plug-in is not installed Optimize the list page code output 1.2 Fix the comment function and add a custom homepage title 1.1 Fix the comment reply asymmetry function Add a separate title setting function on the homepage Add the website favicon.ico icon Add one...
👁 199
Responsive Marketing Strategy – Cultural Media Company Website Template 0494

Responsive Marketing Strategy – Cultural Media Company Website Template 0494 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for marketing and cultural media companies specializing in creative marketing strategies. It enables you to showcase brand development projects, cultural media services, innovative campaigns, and successful case studies. This template helps cultural media firms demonstrate their professional expertise online and attract brand clients. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Common Questions About EyouCMS Installation...
👁 44
Modification of typecho paging style

Modification of typecho paging style Program Notes Typecho

Sir, times have changed! Typecho is currently the most perfect solution, because Baidu can only see the code of fixed thinking. The actual generated HTML code is breathtakingly clean and fully customized, including adding classes to the li element, adding classes to the a element, adding classes to the previous page and next page, and removing the li tags that come with typecho to express more. I can even add some text to the content inside...
👁 517