我的问题(可能在您的计算机中没有发生)
我有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"
?>
Run Code Online (Sandbox Code Playgroud)
第二个脚本仅包含一个变量
<?php $num=1; ?>
Run Code Online (Sandbox Code Playgroud)
我希望结果为“ 2”,但似乎第二个include不会读取file_put_contents所做的更改。
我的第一个猜测是file_put_contents函数中可能存在并发问题,因此当执行第二个include时,第二个文件并未真正更改。
我尝试通过将第一个脚本更改为此来测试我的猜测:
<?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('<', '>'),
file_get_contents('second.php')) . '</pre>';
include('second.php');
echo $num;
?>
Run Code Online (Sandbox Code Playgroud)
我真的很惊讶地发现程序的结果是这样的:
<?php $num=4; ?>
3
Run Code Online (Sandbox Code Playgroud)
这意味着file_put_contents可以正确读取文件(换句话说,文件实际上已经被物理更改),但是“ include”仍使用第一个值。
我的问题
我已阅读此问题,但未找到答案:
在PHP中动态更改的文件。有时在include(),ftp_put()中看不到更改
临时解决方法
使用eval似乎是临时解决方法。这并不优雅,因为评估通常与安全漏洞相关联。
<?php
require('second.php');
$num ++;
file_put_contents('second.php', '<?php $num='.$num.'; ?>');
echo '<pre>' . str_replace(array('<','>'), array('<', '>'), 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;
?>
Run Code Online (Sandbox Code Playgroud)
结果如下:
<?php $num=10; ?>
9
10
Run Code Online (Sandbox Code Playgroud)
可能您已经安装并启用了OPcache(自Php 5.5:添加了OPcache扩展名以来),是否在缓存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
?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
755 次 |
| 最近记录: |