PHP 缓存包含文件


PHP caching include file

我在test.php中有以下测试代码:

<?php
$step = $_GET['step'];
switch($step) {
  case 1:
    include 'foo.php';   # line 5
    file_put_contents('foo.php', '<?php print "bar''n"; ?>');
    header('Location: test.php?step=2');
  break;
  case 2:
    print "step 2:'n";
    include 'foo.php';
  break;
}
?>

FOO.php最初有以下内容:

<?php print "foo'n"; ?>

当我在浏览器中调用 test.php?step=1 时,我希望得到以下输出:

step 2:
bar

但是我得到这个输出:

step 2:
foo

当我注释掉第 5 行中的包含时,我得到了想要的结果。结论是,PHP 缓存了 foo.php 的内容。当我使用 step=2 重新加载页面时,我也得到了想要的结果。

现在。。。为什么会这样以及如何避免这种情况?

假设你使用OPcache,opcache.enable = 0工作。

更有效的方法是使用

opcache_invalidate ( string $script [, boolean $force = FALSE ] )

这将从内存中删除脚本的缓存版本,并强制 PHP 重新编译。

请注意,opcache_invalidate并不总是可用的。因此,最好检查它是否存在。另外,您应该同时检查opcache_invalidateapc_compile_file

以下函数将执行所有操作:

    public static function clearCache($path){
        if (function_exists('opcache_invalidate') && strlen(ini_get("opcache.restrict_api")) < 1) {
            opcache_invalidate($path, true);
        } elseif (function_exists('apc_compile_file')) {
            apc_compile_file($path);
        }
    }