Re: incrementing a number from a text file

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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";

?>

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux