Unfortunately, it still doesn't prevent someone from editing the file whilst ignoring whether or not some other process is already editing it.
Also, I would recommend opening the file for reading *and* writing. Then you read the file contents *without* releasing the filehandle. Then you write to the file. So for that whole time the OS knows that the file is open by a process, and your "is file in use" test will work.
On Mar 11, 2005, at 11:00 AM, Ariceaga, Luis TQM wrote:
Is it possible to let the OS handle the collisions?
For example:
$last_value = system('cat counter.txt', $retval); $last_value++; $result = system('echo $last_value > counter.txt', $retval);
...just a suggestion!
Regards /Luis
-----Original Message----- From: Richard Lynch [mailto:ceo@xxxxxxxxx] Sent: Thursday, March 10, 2005 3:14 PM To: Ross Hulford Cc: php-general@xxxxxxxxxxxxx Subject: Re: incrementing a number from a text file
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 dothis.
That's what you *THINK* you want to do :-)
But what happens when *TWO* users hit that same script at exactly the same time.
At best, you get:
User1 User2 Reads 9 Reads 9 Writes 10 Writes 10
and when you should have 11, you've only got 10.
[aside] "My amp goes to 11!" [/aside]
But it's worse than that: It's entirely poassible that your script, instead of having two users write "10" one after the other, will have two users both trying to write "10" at EXACTLY the same time.
The result is comparable to a head-on collision between two trains. Your file is TOAST.
This is why so many early "hit counter" scripts back in the day were always getting messed up and reset to 0.
What you really want, almost for sure, is an SQL database with "sequences"
You have to forge those in MySQL by making a table with auto_increment.
You *can* use http://php.net/flock, but even that is a Bad Idea, because
flock under Un*x is self-imposed -- If some *other* program/script/user
decides not change that file and doesn't use flock, well, they're not
STOPPED from doing that.
flock is therefore all too subject to human fallibility when you re-work, re-write, or add more code to your system.
The SQL guys have worked out this problem, in all respects.
This is one of those things that SEEMS so simple that turns out to be a hell of a lot more involved than you thought at first. So it goes.
-- Like Music? http://l-i-e.com/artists.htm
-- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
-- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
--
Kurt Yoder http://yoderhome.com
-- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php