请帮助改善我的pHp缓存?

时间:2011-08-26 15:36:21

标签: php caching

我已经在互联网上阅读了一些关于php缓存的内容。 在我使用的那一刻,这个系统缓存我的页面:

这是在页面的开头

<?php

    // Settings
    $cachedir = 'cache/'; // Directory to cache files in (keep outside web root)
    $cachetime = 600; // Seconds to cache files for
    $cacheext = 'html'; // Extension to give cached files (usually cache, htm, txt)

    // Ignore List
    $ignore_list = array(
        'addedbytes.com/rss.php',
        'addedbytes.com/search/'
    );

    // Script
    $page = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; // Requested page
    $cachefile = $cachedir . md5($page) . '.' . $cacheext; // Cache file to either load or create

    $ignore_page = false;
    for ($i = 0; $i < count($ignore_list); $i++) {
        $ignore_page = (strpos($page, $ignore_list[$i]) !== false) ? true : $ignore_page;
    }

    $cachefile_created = ((@file_exists($cachefile)) and ($ignore_page === false)) ? @filemtime($cachefile) : 0;
    @clearstatcache();

    // Show file from cache if still valid
    if (time() - $cachetime < $cachefile_created) {

        //ob_start('ob_gzhandler');
        @readfile($cachefile);
        //ob_end_flush();
        exit();

    }

    // If we're still here, we need to generate a cache file

    ob_start();

?>

我的HTML代码在这里.............

以下代码位于我页面的页脚。

<?php

    // Now the script has run, generate a new cache file
    $fp = @fopen($cachefile, 'w'); 

    // save the contents of output buffer to the file
    @fwrite($fp, ob_get_contents());
    @fclose($fp); 

    ob_end_flush(); 

?>

我需要一些东西,这段代码没有它们:

  • gzip的
  • 过期的缓存在过期后不会自动删除。

还想问一下,如果这段代码可以安全使用,如果有人可以建议更好的一个或者某些东西来改进当前的代码,那就太棒了

感谢您阅读这篇文章。 最好的祝福 MEO

3 个答案:

答案 0 :(得分:2)

….
  // Show file from cache if still valid
  if (time() - $cachetime < $cachefile_created) {

      //ob_start('ob_gzhandler');
      echo gzuncompress(file_get_contents($cachefile));
      //ob_end_flush();
      exit();

  } else {
    if(file_exists($cachefile) && is_writable($cachefile)) unlink($cachefile)
  }            
….

和     

    // Now the script has run, generate a new cache file
    $fp = @fopen($cachefile, 'w'); 

    // save the contents of output buffer to the file
    @fwrite($fp, gzcompress(ob_get_contents(), 9));
    @fclose($fp); 

    ob_end_flush(); 

?>

答案 1 :(得分:1)

使用ob_start("ob_gzhandler");启动gzipped缓冲(它将负责确定客户端是否可以实际接受/需要gzip压缩数据并相应地调整内容。)

删除缓存的文件:

if (time() - $cachetime < $cachefile_created) {
    @readfile($cachefile);
    //ob_end_flush();
    exit();
} else {
    unlink($cachefile);
    exit();
}

答案 2 :(得分:0)

但是在写入文件时,可能会出现延迟或错误,并且有人请求该页面。您应该使用flock来克服Error during file write in simple PHP caching

中提到的问题

页面末尾有这样的内容

<?php   
        $fp = @fopen($cachefile, 'w'); 
    if (flock($fp, LOCK_EX | LOCK_NB)) {
    fwrite($fp, gzcompress(ob_get_contents(), 9));
    flock($fp, LOCK_UN);
    fclose($fp); 
    }

    ob_end_flush(); ?>
相关问题