【问题标题】:Automatically create cache file with php用php自动创建缓存文件
【发布时间】:2013-01-03 10:01:45
【问题描述】:

我一直在我的网站上使用基于 this link 的基本缓存系统

到目前为止,它对我想做的任何事情都很有效。

$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 查询,我花了相当多的时间优化它,但是当我在 mysql 中查询它时,它仍然需要大约 10 秒才能运行,甚至在网站上运行更长时间。有时,当我收到以下消息时,它似乎超时了。

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(在服务器上)将文件写入缓存。

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

【问题讨论】:

  • 如果你有 linux 服务器 - cron 作业

标签: php performance caching


【解决方案1】:

我建议你使用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 作业以自动运行它。

【讨论】:

  • Php Speedy 唯一的缺点是改变了 css 和 js 扩展。验证器可能会让您感到沮丧。
猜你喜欢
  • 2013-12-22
  • 2015-09-13
  • 1970-01-01
  • 1970-01-01
  • 2021-10-26
  • 1970-01-01
  • 1970-01-01
  • 2011-09-29
  • 2012-05-22
相关资源
最近更新 更多