PHP 在不破坏页面的情况下缓存脚本

PHP caching script without breaking page

我正在使用一个简单的 PHP-缓存脚本,它看起来像这样:

<?php

$url = $_SERVER["SCRIPT_NAME"];

$actual_link = $_SERVER['REQUEST_URI'];

$id = basename($actual_link);

$cachefile = 'cache/cached-items/cached-'.$id.'-content.html';
$cachetime = 2419200; 

if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
    echo "<!-- Cached copy, generated ".date('H:i', filemtime($cachefile))." -->\n";
    readfile($cachefile);
    exit;
} 
ob_start(); // Start the output buffer

// PHP Code which should get cached //


// Cache the contents to a cache file
$cached = fopen($cachefile, 'w');

fwrite($cached, ob_get_contents());
fclose($cached);
ob_end_flush(); // Send the output to the browser


// Another script which should't get cached

?>

如果缓存文件可用,脚本将退出并停止执行不应被缓存的其余 php 代码。它还破坏了整个页面的html。

我正在寻找“exit”语句的解决方案,如果缓存文件可用。

我不知道我是否理解你的意思,但我会这样做:

<?php

$url = $_SERVER["SCRIPT_NAME"];

$actual_link = $_SERVER['REQUEST_URI'];

$id = basename($actual_link);

$cachefile = 'cache/cached-items/cached-'.$id.'-content.html';
$cachetime = 2419200; 

if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
    echo "<!-- Cached copy, generated ".date('H:i', filemtime($cachefile))." -->\n";
    readfile($cachefile);
} 
else {
    ob_start(); // Start the output buffer

    // PHP Code which should get cached //


    // Cache the contents to a cache file
    $cached = fopen($cachefile, 'w');

    fwrite($cached, ob_get_contents());
    fclose($cached);
    ob_end_flush(); // Send the output to the browser
}

// Another script which should't get cached

?>