My problem (probably doesn't occur in your computer)
I have 2 PHP scripts.
The first script read include the second script to get a variable, change the value, and do file_put_contents to change the second script.
<?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"
?>
The second script simply contains a variable
<?php $num=1; ?>
I expect the result to be "2", but it seems that the second include doesn't read changes made by file_put_contents.
My first guess was there might be concurrency issue in file_put_contents function, so that the second file was not really changed when the second include executed.
I try to test my guess by changing the first script into this:
<?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;
?>
I was really surprised to find that the result of the program is this:
<?php $num=4; ?>
3
This means that file_put_contents read the file correctly (in other words, the file has really been physically changed), but "include" still use the first value.
My Questions
- Can anyone explain this?
- Is there any workaround (instead of "sleep()") to make "include" read the changes?
I have read this question and found no answer:
Dynamically changed files in PHP. Changes sometimes are not visible in include(), ftp_put()
Temporary workaround
Using eval seems to be temporary workaround. This is not elegant since eval is usually associated with security hole.
<?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;
?>
This is the result:
<?php $num=10; ?>
9
10