在PHP中进行服务器端输出缓存的最佳方法是什么?

Pau*_*jan 6 php apache indexing caching apc

index.php现在非常复杂,我想每小时只运行一次.实现这一目标的最佳方法是什么?我有过一些想法

  • 把它放在APC中apc_store($page, 60*60*)- 我觉得这不是APC的用途,可能会对我网站的其他部分做些坏事
  • 将输出保存到某个文件系统 - 然后apache需要在某个地方进行写访问,这可能很麻烦
  • 以某种方式设置apache为我做缓存 - 这可能吗?

Pau*_*jan 1

我对罗尔夫和贾米特林的答案略有不同。

创建3个文件:

索引.html

<meta http-equiv="refresh" content="0;url=/index_update.php" />
Run Code Online (Sandbox Code Playgroud)

索引.php

<?php // do all your normal stuff ?>
Run Code Online (Sandbox Code Playgroud)

索引更新.php

<?php

$file = "index.html";
$time = 60 * 10 - (time() - filemtime($file));

# this is on the first install 
if (filemtime($file) != filectime($file))
    $time = 0;

if ($time > 0) {
    die("Data was already updated in the 10 minutes. Please wait another " . ($time) . " seconds.");
}

ob_start();
require "index.php";
$data = ob_get_contents();

$fp = fopen($file, "w");
fwrite($fp, $data);
fclose($fp);

header("Location: /");
Run Code Online (Sandbox Code Playgroud)

然后是一个定时任务:

*/15 * * * * curl http://example.com/index_update.php
Run Code Online (Sandbox Code Playgroud)

因此,如果有人在生产推送后偶然发现该页面,他们将透明地为您创建一个新的 index.html,否则,您的 cronjob 将每 15 分钟执行一次。

只需确保您的 apache 服务器可写index.html即可。如果这听起来很可怕,那么只需让您的 cronjobphp index_update.php以另一个具有index.html写入权限的用户身份运行即可。但您无法访问所有 apache 环境。

希望这对您有所帮助,欢迎评论。