Re: incrementing a number from a text file

From: Date: Fri, 11 Mar 2005 15:27:08 +0000
Subject: Re: incrementing a number from a text file
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-210506@lists.php.net to get a copy of this message
At 03:14 PM 3/10/2005, Richard Lynch wrote:
I want to read a number from an external (txt) file and increment it.then save the number back on the text file. I know this is possible but want a simple amd economical way to do this. That's what you *THINK* you want to do :-) But what happens when *TWO* users hit that same script at exactly the same time.
Richard has a good idea about using mysql to do this. Some things I have not tried, but might also do for you is php's flock http://www.php.net/flock . Or go to http://www.php.net/fopen and search the page for "lock" (no quotes). The example you might want was the 4th instance of that word that I found. <?php #going to update last users counter script since #aborting a write because a file is locked is not correct. $counter_file = '/tmp/counter.txt'; clearstatcache(); ignore_user_abort(true); ## prevent refresh from aborting file operations and hosing file if (file_exists($counter_file)) { $fh = fopen($counter_file, 'r+'); while(1) {
     if (flock($fh, LOCK_EX)) {
        #$buffer = chop(fgets($fh, 2));
        $buffer = chop(fread($fh, filesize($counter_file)));
        $buffer++;
        rewind($fh);
        fwrite($fh, $buffer);
        fflush($fh);
        ftruncate($fh, ftell($fh));
        flock($fh, LOCK_UN);
        break;
     }
} } else { $fh = fopen($counter_file, 'w+'); fwrite($fh, "1"); $buffer="1"; } fclose($fh); print "Count is $buffer"; ?>

« previous php.general (#210506) next »