For the record, the example given here has an explicit command to truncate the file, however with a 'write mode' of 'w', it will do this for you automatically, so the truncate call is not needed.
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
SplFileObject::flock — 簡易なファイルロックを行う
flock() と同じ簡易な方法でファイルをロックもしくはロック解除する。
例1 SplFileObject::flock() の例
<?php
$file = new SplFileObject("/tmp/lock.txt", "w");
if ($file->flock(LOCK_EX)) { // 排他ロックを行う
$file->ftruncate(0); // ファイルを丸める
$file->fwrite("ここで何かを書き出します\n");
$file->flock(LOCK_UN); // ロックを解除する
} else {
echo "ロックを取得できませんでした!";
}
?>
For the record, the example given here has an explicit command to truncate the file, however with a 'write mode' of 'w', it will do this for you automatically, so the truncate call is not needed.