Re: Counter has gremlins

From: Date: Tue, 18 Feb 2003 00:51:47 +0000
Subject: Re: Counter has gremlins
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-135934@lists.php.net to get a copy of this message
I believe this is a concurrency problem... 2 PHP scripts can run at the same time and the problem is that your first script gets as far as the unlink thus deleting the file. Then the 2nd script is ran (at the same time) and trys to open the file which doesn't exist, therefore it reads a num of 0. Then control returns to script 1 which saves the number num (which is a valid count), and finish... Script 2 continues and saves the num 0, and therefore your counter gets reset. Its all a problem of concurrency and the fact that more than one thing can happen at a time. There are a few solutions. 1) Use MySQL or another database which limits reading/writing to the data so that problems like this do not occur. 2) Use a flocking method which locks the file between the reading and writing so that no other script can interfeare... I'm unsure on how good this method is with PHP, so I suggest the first. Andrew ----- Original Message ----- From: "Brian V Bonini" <b-bonini@cox.net> To: "PHP Lists" <php-general@lists.php.net> Sent: Tuesday, February 18, 2003 12:45 AM Subject: [PHP] Counter has gremlins > I have this basic counter: > > <?php > $counterFile = "./counter.txt"; > function displayCounter($counterFile) { > global $counted; > $fp = fopen($counterFile, 'rw'); > $num = fgets($fp,7); > if (!$counted) { > $num += 1; > unlink("$counterFile"); > exec("echo $num > $counterFile"); > } > print "Visitor #$num"; > } > if (!file_exists($counterFile)) { > exec("echo 1 > $counterFile"); > } > displayCounter($counterFile); > > ?> > > Works like a charm but every so often for no apparent reason it resets > to 0. > > Anyone see anything wrong here to cause that? > > > -- > PHP General Mailing List (http://www.php.net/) > To unsubscribe, visit: http://www.php.net/unsub.php > >

« previous php.general (#135934) next »