PHP 页面的简单缓存代码失败 - 如何在提交表单时使缓存失效


Simple Caching code for PHP Pages Fails - How to invalidate cache when form is Submitted

<?php
// cache - will work online - not locally
// location and prefix for cache files
define('CACHE_PATH', "siteCache/"); 
// how long to keep the cache files (hours)
define('CACHE_TIME', 12); 
// return location and name for cache file 
function cache_file() 
{ 
    return CACHE_PATH . md5($_SERVER['REQUEST_URI']); 
}
// display cached file if present and not expired 
function cache_display() 
{ 
    $file = cache_file(); 
    // check that cache file exists and is not too old 
    if(!file_exists($file)) return; 
    if(filemtime($file) < time() - CACHE_TIME * 3600) return; 
    // if so, display cache file and stop processing
    readfile($file);
    exit; 
} 
// write to cache file 
function cache_page($content) 
{ 
    if(false !== ($f = @fopen(cache_file(), 'w'))) { 
        fwrite($f, $content);
        fclose($f); 
    } 
    return $content; 
} 
// execution stops here if valid cache file found
cache_display(); 
// enable output buffering and create cache file 
ob_start('cache_page');
?>

这是我在数据库文件中的动态网站中使用的缓存代码。每个页面的顶部都包含此代码。

<?php session_start();
include("db.php"); ?>
页面

正在缓存并正常工作,但在表单提交、用户登录、通过页面的变量上,什么也没发生。正在显示旧页面。我如何使用此缓存代码,以便它可以工作,但站点也保持功能。

我想知道WordPress插件是如何做到的。Wp超级缓存和W3T缓存缓存所有内容,但博客仍然有效。我应该有选择地在网站的某些部分使用它吗?

喜欢这个:

<?php
// TOP of your script
$cachefile = 'cache/'.basename($_SERVER['SCRIPT_URI']);
$cachetime = 120 * 60; // 2 hours
// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile))) {
    include($cachefile);
    echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))." -->";
    exit;
}
ob_start(); // start the output buffer
// Your normal PHP script and HTML content here
// BOTTOM of your script
$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 the file
ob_end_flush(); // Send the output to the browser
?>

但它也不会工作,因为它是关于pageURL(整个页面缓存),而不是页面中的选择性内容。

请指教。有没有简单的脚本可以做到这一点。梨::Cache_Lite看起来不错,但看起来很难实现。

更新:我用过Cache_Lite。它是一样的。缓存所有内容或包含的 php 文件。可以使用的配置选项很少。但如果作为一个整体使用,它也会忽略获取、发布、会话数据更新......并且将显示以前的缓存页面,除非它们被删除。

我认为您可以将显示与逻辑分开。

我的意思是,更改表单的 action 属性并将其指向没有缓存逻辑的 php(您必须使用令牌或会话或其他东西检查引用器或其他参数,以避免像 CSRF 这样的安全问题)。

我想指出的另一件事是,您应该只缓存访问量最大的页面(即主页),通常您没有"一刀切"的缓存,最好不要担心没有速度/加载问题的页面。或者,如果速度问题来自数据库查询,则最好缓存数据(应在实现缓存之前分析应用程序)。

另一种可行的方法是检查请求方法,如果使用 $_SERVER['REQUEST_METHOD'] == 'POST' 进行 POST 并禁用缓存(假设您的所有表单都使用 POST 方法)。