typecho 缓存文章开发日记

前言

今天随便研究了一下,文件缓存。用于typecho缓存
(适合人群:长期不更🐕。例如我)

贴一下代码

修改functions.php代码,添加下面代码(记得修改主题名


// 缓存放入头部
function cache(){
        

        //获取域名后面几位,正则替换,把/和.替换成@
        $string = $_SERVER['REQUEST_URI'];
        $stringx =  explode("?",$string);
        $replacement = '@';
        $pattern = '/\//i';
        $pattern1 = '/\./i';
        $string1 =  preg_replace($pattern, $replacement, $stringx[0]);
        $string2 =  preg_replace($pattern1, $replacement, $string1);
        
        //当前文件地址,StarrySky是主题名,自己修改
        $file = "usr/themes/StarrySky/cache/".$string2.".txt";
        
        //获取当前完整地址
        $eUrl = (isHTTPS() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; 
        
        
        //get写入命令
        $cachexr = $_GET['cachexr'];
        
        
        

        //判断文件在不在
        
        if(!file_exists($file))
        {
            //"当前目录中,文件不存在",新写入一个空文件先
            $myfile = fopen($file, "w") or die("Unable to open file!");
            $txt = '';
            fwrite($myfile, $txt);
            //记得关闭流
            fclose($myfile);
            //get更新缓存
            //get一个写入命令,获取值,并且写入
            $content = file_get_contents($eUrl.'?cachexr=ok');
            $myfile = fopen($file, "a") or die("Unable to open file!");
            $txt = $content;
            fwrite($myfile, $txt);
            fclose($myfile);
            
        }else{
            if($gxml!=='ok' && $cachexr!=='ok'){
                // 文件存在
                $jc = file_get_contents($file); //将整个文件内容读入到一个字符串中
                echo $jc;
                exit;
            }
            
        }
        
    

}
//获取当前域名
function isHTTPS()
{
    if (defined('HTTPS') && HTTPS) return true;
    if (!isset($_SERVER)) return FALSE;
    if (!isset($_SERVER['HTTPS'])) return FALSE;
    if ($_SERVER['HTTPS'] === 1) {  //Apache
        return TRUE;
    } elseif ($_SERVER['HTTPS'] === 'on') { //IIS
        return TRUE;
    } elseif ($_SERVER['SERVER_PORT'] == 443) { //其他
        return TRUE;
    }
    return FALSE;
}

在主题目录下创建

名字为cache文件夹

然后再header.php文件,也就是index.php引用的头部文件

最前面,第一行放入

<?php cache() ?>