file_put_contents problem

Hi

I have a problem with the file_put_contents function.

Here is a part of my code :
[php]$data = array(‘a’=>rand(),‘b’=>rand(),‘c’=>rand());
file_put_contents($filename,json_encode($data), LOCK_EX);[/php]

Sometimes, the string written in the file is not correct : for instance I got {"a":71395911,"b":8808,"c":17}6}.

That source code is inside a function which can NOT be called twice at the same time. Nevertheless, I have other php scripts which can read the file.

I succeeded in finding a way to reproduce the bug :
[php] <?php
// File “write.php”
set_time_limit(0);
ignore_user_abort(true);
$filename = ‘test.json’;
$puiss = array();
for($i=0;$i<10;$i++){
$puiss[$i]=pow(10,$i+1);
}
for ($i = 0; $i < 100000; $i++) {
$data = array(‘a’ => (mt_rand()%$puiss[rand()%10]), ‘b’ => (mt_rand()%$puiss[rand()%10]), ‘c’ => (mt_rand()%$puiss[rand()%10]));
file_put_contents($filename, json_encode($data), LOCK_EX);
}
echo ‘done’;
?>[/php]

[php] <?php
// File read.php
set_time_limit(0);
ignore_user_abort(true);
$filename = ‘test.json’;
for ($i = 0; $i < 1000000; $i++) {
$data = file_get_contents($filename);
if (json_decode($data, true) == false) {
echo ‘Error !! - "’.$data.’"’;
break;
}
}
echo ‘done’;
?>[/php]

If you run the two php scripts in parallel, the read.php script stops and displays : Error “” (so $data is empty).

And if I add the condition strlen($data)>0, I got {"a":71395911,"b":8808,"c":17}6}

Could you help me please ? :slight_smile:

Thks :wink:

bump

Sponsor our Newsletter | Privacy Policy | Terms of Service