note 30289 added to function.flock
| From: | ags at rack1 dot php dot net | Date: | Thu, 13 Mar 2003 04:11:15 +0000 |
| Subject: | note 30289 added to function.flock | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-45200@lists.php.net to get a copy of this message | ||
I am not certain how well this works (I've never had problems, but I haven't stress-tested
it), but I have been using this solution for performing safe file locking and writing:
if($fl = fopen($filepath))
if(flock($fl, LOCK_EX))
{
fseek($fl, 0);
ftruncate($fl, 0);
fwrite($fl, $whateverdata);
fflush($fl);
flock($fl, LOCK_UN);
fclose($fl);
}
This "cheats" and opens a file for writing by opening it for append (which doesn't
truncate), then acquiring the lock first before performing any truncation or actual write
operations. Thus, if the file cannot be successfully locked, it won't be changed at all.
I usually like to assemble the data to be written in one large buffer first, so the file is open and
locked for the shortest time possible. This is also friendlier to other scripts that are blocking
on lock.
--
http://www.php.net/manual/en/function.flock.php
http://master.php.net/manage/user-notes.php?action=edit+30289
http://master.php.net/manage/user-notes.php?action=delete+30289
http://master.php.net/manage/user-notes.php?action=reject+30289