note 30289 modified in function.flock by danbrown

From: Date: Mon, 18 May 2009 00:49:18 +0000
Subject: note 30289 modified in function.flock by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155437@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: <?php 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. --was-- 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://php.net/manual/en/function.flock.php

« previous php.notes (#155437) next »