自动创建缓存文件与php


Automatically create cache file with php

我一直在我的网站上使用基于这个链接的基本缓存系统

到目前为止,它对我想做的每件事都很有效。

$cachefile = 'cache/'. basename($_SERVER['QUERY_STRING']) . '.html';
$cachetime = 1440 * 60; 
if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile))) {
  include($cachefile);
  echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))." -->";
  exit;
}
ob_start();
// My html/php code here

$fp = fopen($cachefile, 'w'); // open the cache file for writing
fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file
fclose($fp); // close
ob_end_flush(); // Send to browser

然而,我有几个页面更详细的mysql查询,我花了相当多的时间优化它,但它仍然需要大约10秒运行,当我在mysql查询它,甚至更长时间在网站上。有时,当我收到以下消息时,它似乎超时了。

The proxy server received an invalid response from an upstream server.
The proxy server could not handle the requestGET http://www.example.com
Reason: Error reading from remote server

这不是一个大问题,因为我使用上面的缓存系统,只有第一个人点击它的一天得到延迟,其余时间的用户得到缓存的页面,所以它实际上是相当快的。

我不想成为每天第一个访问页面的人,并自动执行此过程,因此每天17:00(在服务器上)文件被写入缓存。

我怎样才能最好地做到这一点?

我建议你使用Php Speedy或这可能会有所帮助:

<?php
function getUrl () {
    if (!isset($_SERVER['REQUEST_URI'])) {
    $url = $_SERVER['REQUEST_URI'];
    } else {
    $url = $_SERVER['SCRIPT_NAME'];
    $url .= (!empty($_SERVER['QUERY_STRING']))? '?' . $_SERVER[ 'QUERY_STRING' ] : '';
    }
    return $url;
}
//getUrl gets the queried page with query string
function cache ($buffer) { //page's content is $buffer
    $url = getUrl();
    $filename = md5($url) . '.cache';
    $data = time() . '¦' . $buffer;
    $filew = fopen("cache/" . $filename, 'w');
    fwrite($filew, $data);
    fclose($filew);
    return $buffer;
}
function display () {
    $url = getUrl();
    $filename = md5($url) . '.cache';
    if (!file_exists("/cache/" . $filename)) {
    return false;
    }
    $filer = fopen("cache/" . $filename, 'r');
    $data = fread($filer, filesize("cache/" . $filename));
    fclose($filer);
    $content = explode('¦', $data, 2);
    if (count($content)!= 2 OR !is_numeric($content['0'])) {
        return false;
    }
    if (time()-(100) > $content['0']) { // 100 is the cache time here!!!
        return false;
    }
        echo $content['1'];
        die();
}
// Display cache (if any)
display();  // if it is displayed, die function will end the program here.
// if no cache, callback cache
ob_start ('cache');
?>

只要在任何需要缓存的地方包含这个脚本,并设置一个cron作业来自动运行它。