note 34575 added to function.fopen

From: Date: Thu, 31 Jul 2003 06:39:26 +0000
Subject: note 34575 added to function.fopen
Groups: php.notes 
Request: Send a blank email to php-notes+get-53050@lists.php.net to get a copy of this message
I offer the following script for updating a counter, using methods gleaned from various posts on file operations... <? $counter_file = 'somefile.txt'; clearstatcache(); ignore_user_abort(true); ## prevent refresh from aborting file operations and hosing file $fh = fopen($counter_file, 'r+b'); ## use 'r+b' so file can be read and written if ($fh) { if (flock($fh, LOCK_EX)) ## don't do anything unless lock is successful { $count = fread($fh, filesize($counter_file)); rewind($fh); $count++; fwrite($fh, $count); fflush($fh); ftruncate($fh, ftell($fh)); ## better than truncating to 0 before writing, per 04-Mar-2003 comment below flock($fh, LOCK_UN); } else echo "Could not lock counter file '$counter_file'"; fclose($fh); } else echo "Could not open counter file '$counter_file'"; ignore_user_abort(false); ## put things back to normal echo "counter is at $count"; ?> ---- Manual Page -- http://www.php.net/manual/en/function.fopen.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+34575 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+34575&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+34575&report=yes

« previous php.notes (#53050) next »