문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top