代码之家  ›  专栏  ›  技术社区  ›  Jacob Relkin

如何在PHP中将动态页面缓存到平面文件中?

php
  •  2
  • Jacob Relkin  · 技术社区  · 16 年前

    我正在尝试滚动缓存系统以减少数据库上的负载。

    我想能够比较平面文件上次更新的时间戳 以确保文件最近更新的时间不太长。

    代码如下:

    $cache_file = $_GET[ 'page_id' ] . '.html';
    
    function cache() {
    
        // Here i want to get the timestamp of the file that was previously cached, 
        // if it exists.
        // If the file doesn't exist, create it.
        // If it does exist, check last modified time, if it's too long ago, then overwrite
        // the file.
    
    
        $ob = ob_get_contents();
    
        file_put_contents( $cache_file, $ob );
    
    }
    
    function loadFromCache( $page_id ) {
        $file_name = $page_id . '.html';
        if( ! file_exists( $file_name  ) ) {
             return false;
        }
        readfile( $file_name );
        return true;
    }
    

    谢谢您。

    3 回复  |  直到 15 年前
        1
  •  2
  •   Amber    16 年前

    你可以使用 filemtime() 获取文件的修改时间。

        2
  •  -2
  •   Sergey Kuznetsov    16 年前

    如果要获取当前文件最后一次修改的时间戳,可以使用以下代码:

    <?php
        $stat = (stat(__FILE__));
        echo 'Document last updated: ', date('M d Y', $stat['mtime']);
    ?>
    
        3
  •  -2
  •   Toby Allen mercator    16 年前

    为什么不使用其中一个php缓存选项 out there ?php加速器还是php:apc?这些为您提供了一个现成的滚动解决方案。

    推荐文章