简体   繁体   中英

PHP caching include file

I have the following test code in 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 initially has the following content:

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

When I call test.php?step=1 in my browser I would expect the following output:

step 2:
bar

But I get this output:

step 2:
foo

When I comment out the include in line 5, I get the desired result. The conclusion is, that PHP caches the content of foo.php. When I reload the page with step=2 I also get the desired result.

Now... why is this and how to avoid this?

Assuming you use OPcache, opcache.enable = 0 works.

A more efficient method is to use

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

This will remove the cached version of the script from memory and force PHP to recompile.

Note that opcache_invalidate is not always available. So it is better to check if it exists. Also, you should check both of opcache_invalidate and apc_compile_file .

Following function will do everything:

    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);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM