0

値を保存するファイルがあります。ユーザーはそのファイルにデータを追加でき、そのファイルのカウンターが更新されます。ただし、2人のユーザーがファイルを開くと、同じカウンター($arr['counter'])を取得します。私は何をすべきか?たぶん、1人のユーザーのファイルをロックし、彼がカウンターを更新してファイルに何かを追加した後でロックを解除できますか?または、PHPを開くと、ファイルはすでにロックされているので、心配する必要はありませんか?これが私の現在のコードです:

    $handle = fopen($file, 'r');
    $contents = fread($handle, filesize($file));
    fclose($handle);       

    $arr = json_decode($contents);

    //Add stuff here to $arr and update counter $arr['counter']++

    $handle = fopen($file, 'w');
    fwrite($handle, json_encode($arr));   
    fclose($handle);      
4

1 に答える 1

1

PHPにはflock、ファイルに書き込む前にファイルをロックする関数があります。たとえば、

$handle = fopen($file, 'r');
$contents = fread($handle, filesize($file));
fclose($handle);       

$arr = json_decode($contents);

//Add stuff here to $arr and update counter $arr['counter']++

$handle = fopen($file, 'w');
if(flock($handle, LOCK_EX))
{
    fwrite($handle, json_encode($arr));
    flock($handle, LOCK_UN);        
}
else
{
    // couldn't lock the file
}
fclose($handle); 
于 2012-11-04T19:05:00.537 に答える