Question

I am trying to block a file using the flock() function to avoid an overwrite error but the counter often resets (probably for a reading issue).

numeri.txt (counter)

4895|533753

frame.php (PHP file)

$filename="numeri.txt";
$contents=file_get_contents($filename);
if(($fp=@fopen($filename,'w'))!==false)
{
    if(flock($fp,LOCK_EX))
    {
        $contents=explode("|",$contents);
        $clicks=$contents[0];
        $impressions=$contents[1]+1;
        fwrite($fp,$clicks."|".$impressions);
        flock($fp,LOCK_UN);
    }
    fclose($fp);
}

Sometimes the counter returns "|1" instead of "4895|533754".

How can I fix it?

Was it helpful?

Solution

If two threads will execute your code almost simultaneusly with the small delay, the 1st thread will open file for write and erase it contents before locking.

The 2nd thread will read the empty file contents, wait for lock release, and then overwrite the correct data.

The solution is to open file not in "w", but in "a" or "c" mode and then use fwrite, fseek and ftruncate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top