PHP包括不读取源文件的更改

时间:2014-06-06 04:34:59

标签: php

我的问题(可能不会在您的计算机中出现)

我有2个PHP脚本。

第一个脚本读取包括获取变量的第二个脚本,更改值,以及执行file_put_contents以更改第二个脚本。

<?php
include('second.php'); // in second.php, $num defined as "1" 
$num ++;               // now $num should be "2"
// Change content of second.php
file_put_contents('second.php', '<?php $num='.$num.'; ?>'); 
include('second.php'); // Now here is the problem, $num's value is still "1"
echo $num;             // and I get an unexpected result "1"
?>

第二个脚本只包含一个变量

<?php $num=1; ?>

我希望结果为&#34; 2&#34;,但似乎第二个包括没有读取file_put_contents所做的更改。

我的第一个猜测是file_put_contents函数中可能存在并发问题,因此当第二个包含执行时,第二个文件并未真正更改。

我尝试通过将第一个脚本更改为此来测试我的猜测:

<?php
include('second.php');
$num ++;
file_put_contents('second.php', '<?php $num='.$num.'; ?>');
// show the contains of second.php
echo '<pre>' . str_replace(array('<','>'), array('&lt;', '&gt;'),
    file_get_contents('second.php')) . '</pre>'; 
include('second.php');
echo $num;
?>

我很惊讶地发现程序的结果是:

<?php $num=4; ?>
3

这意味着file_put_contents正确读取文件(换句话说,文件实际上已被物理更改),但是&#34; include&#34;仍然使用第一个值。

我的问题

  1. 任何人都可以解释一下吗?
  2. 是否有任何解决方法(而不是&#34; sleep()&#34;)来制作&#34;包含&#34;阅读更改?
  3. 我已阅读此问题但未找到答案:

    Dynamically changed files in PHP. Changes sometimes are not visible in include(), ftp_put()

    临时解决方法

    使用eval似乎是临时的解决方法。这并不优雅,因为eval通常与安全漏洞有关。

    <?php
    require('second.php');
    $num ++;
    file_put_contents('second.php', '<?php $num='.$num.'; ?>');
    echo '<pre>' . str_replace(array('<','>'), array('&lt;', '&gt;'), file_get_contents('second.php')) . '</pre>';
    require('file.php');
    echo $num . '<br />';
    eval(str_replace(array('<?php','?>'), array('', ''), file_get_contents('second.php')));
    echo $num;
    ?>
    

    结果如下:

    <?php $num=10; ?>
    9
    10
    

1 个答案:

答案 0 :(得分:3)

您可能已安装并启用了OPcache(自Php 5.5: OPcache extension added起),缓存您的second.php文件?

请参阅phpinfo()是否属实。

如果是,请使用opcache_invalidate('second.php')使缓存文件无效,或使用opcache_reset()重置所有缓存文件。

<?php
include('second.php');
$num ++;

file_put_contents('second.php', '<?php $num='.$num.'; ?>'); 

opcache_invalidate('second.php');//Reset file cache

include('second.php');
echo $num;//2
?>