我们怎样才能在php中完全缓存

Dee*_*ika 4 php caching

我对网络开发更新鲜.

在我的应用程序中,我需要缓存,所以任何人都可以解释如何详细缓存PHP页面?

Ric*_*haw 5

首先在站点的根目录下创建一个名为cache的文件夹,并使其可写.

我有一个名为caching_functions.php的文件,如下所示:

<?
$test_server = $_SERVER['SERVER_NAME'] == "127.0.0.1" || $_SERVER['SERVER_NAME'] == "localhost" || substr($_SERVER['SERVER_NAME'],0,3) == "192";

$caching = !$test_server;

function start_caching($page) {

    global $caching;

    $hash = md5($page);

    if ($caching) {
        $cachefile = "cache/".$hash.".html";

        if (file_exists($cachefile)) {
            include($cachefile);
            echo "<!-- Cached on ".gmdate('r', filemtime($cachefile))." to ".$hash." -->";      
            exit;
        } else {
            ob_start();
            return $cachefile;  
        }       
    }
}

function end_caching($cachefile) {
    global $caching;    
    if ($caching) {     
        $fp = fopen($cachefile, 'w'); 
//      fwrite($fp, ob_get_contents());
        fwrite($fp, preg_replace('!\s+!', ' ', str_replace(array("\n", "\t"),"",ob_get_contents())));
        fclose($fp); 

        ob_end_flush();     
    }
}

function remove_cache() {

    foreach (glob($_SERVER['DOCUMENT_ROOT']."/cache/*.*") as $filename) {
        unlink($filename);
    }
}


?>
Run Code Online (Sandbox Code Playgroud)

然后我把它放在每页的顶部:

在底部:

<? end_caching($cachefile); ?>
Run Code Online (Sandbox Code Playgroud)

这使得页面的第一个请求被转储到缓存文件夹.后续访问使用缓存版本,不要访问数据库或执行任何复杂操作.

我创建了一个名为clearcache.php的页面,并包含caching_functions并获取它只是为了运行remove_cache().这样可以在需要时轻松删除缓存的文件.

这也仅在非本地时运行,因此如果要在本地进行测试,请确保将$ caching更改为1,或者仅在真实服务器上进行测试.

  • 不要忘记使用header()ops将缓存推送给用户. (2认同)