note 72668 added to function.flock

From: Date: Mon, 29 Jan 2007 11:22:59 +0000
Subject: note 72668 added to function.flock
Groups: php.notes 
Request: Send a blank email to php-notes+get-122313@lists.php.net to get a copy of this message
In order to prevent access to some counter file we can use another file as a flag instead of flock(). We change flag's file mode to '400' each time we want to change the counter, and set it back to '600' at the end. If the mode of the flag's file was already changed by another process, we make delayed loop till its mode is set to writable again. The page is refreshing every second so the results can be seen by opening it in two or three browser windows. I tested the script meny times and still my counter is safe. Hope this will help. --------------START------------------ <? header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Cache-Control: no-cache, must-revalidate"); header("Pragma: no-cache"); header("Last-Modified: ".Date("D, d M Y H:i:s")." GMT"); define('COUNT_FILE','count.txt'); //Our counter file define('LOCK_FILE','lock.txt'); //Our lock file. function read_write () { //making our lock file nonwritable chmod(LOCK_FILE, 0400); //reading clearstatcache(); $fpr = fopen(COUNT_FILE, "r"); $count=fread ($fpr, filesize (COUNT_FILE)); fclose($fpr); $count++; //writing $fpw = fopen(COUNT_FILE, "w"); fwrite($fpw,$count); fclose($fpw); //pause the script just to see how it works sleep(1); //making our lock file writable again chmod(LOCK_FILE, 0600); return $count; } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><title>Untitled</title><meta http-equiv="Refresh" content="1"></head><body> <? clearstatcache(); //Check the mode of our lock file if(is_writable(LOCK_FILE)) { print 'is unlocked <br>'; //make changes and show the results print 'changed to '.read_write().'<br>'; }else{ print 'is locked: '; //make loop while(!is_writable(LOCK_FILE)) { print 'pause... '; usleep(rand(5,999)); } //make changes and show the results print '<br>changed at last to '.read_write().'<br>'; }?> </body></html> --------------END------------------ ---- Server IP: 195.54.192.44 Probable Submitter: 81.195.183.186 (proxied: 1.0 SRV-FR) ---- Manual Page -- http://www.php.net/manual/en/function.flock.php Edit -- https://master.php.net/note/edit/72668 Del: integrated -- https://master.php.net/note/delete/72668/integrated Del: useless -- https://master.php.net/note/delete/72668/useless Del: bad code -- https://master.php.net/note/delete/72668/bad+code Del: spam -- https://master.php.net/note/delete/72668/spam Del: non-english -- https://master.php.net/note/delete/72668/non-english Del: in docs -- https://master.php.net/note/delete/72668/in+docs Del: other reasons-- https://master.php.net/note/delete/72668 Reject -- https://master.php.net/note/reject/72668 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#122313) next »