PHP缓存包含文件

5

我在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行的include时,我得到了想要的结果。结论是,PHP缓存了foo.php的内容。当我使用step=2重新加载页面时,也得到了想要的结果。
现在...为什么会这样,并且如何避免这种情况?

1
你正在使用哪个版本的PHP? - britter
2
我猜测你从未被重定向到 ?step=2,因为你在发送 Location 头之前打印了数据(这应该会导致错误)。 - cOle2
如果不覆盖foo.php,注释掉第5行将无法工作。我也查看了foo.php...它已经被修改了。 - Peter
1
如果你仍然认为这是缓存问题,那么你应该检查一下OpCache是否已启用。在你的php.ini文件中,opcache.enable=0。 - britter
虽然我想象中在包含文件后更改它并不是一个好的做法。 - britter
显示剩余4条评论
2个回答

8
假设您正在使用OPcache,opcache.enable = 0 是可行的。
一种更有效的方法是使用:
opcache_invalidate ( string $script [, boolean $force = FALSE ] )

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


5
请注意,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);
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接