Reputation: 11774
I have a file that I'm opening for writing, like this:
if (!$idHandle = fopen($fileName, 'w')) {
echo "Cannot open file ($fileName)";
die();
}
I then enter a loop where I'm incrementing a variable, $beerId
, during each iteration. I want to save that variable to the file I have open, so I use the following code:
if (fwrite($idHandle, $beerId) === FALSE) {
echo "Cannot write to file ($fileName)";
die();
}
$beerId++;
However, this ends up creating a massive string of every beerId I encounter. What I want is to have the file populated ONLY with the last id I left off on.
I realize I could put the write outside of the loop, but the script is volatile and likely to terminate prematurely with an error, so I want to have a reference to the last $beerId variable even in the event of an error that terminates the script before the loop is properly terminated.
Upvotes: 0
Views: 104
Reputation: 10666
You must go back to the beginning of the file because fwrite
keeps track of where it is in the file. Use fseek. Opening and closing the file several times in a loop is expensive and I don't see a reason to do that in this case. You should of course close the file when you're done with it.
You should add this just before you write to the file:
fseek($idHandle, 0);
That will move you to the beginning of the file, since your incrementing values you won't have to worry about removing the previous value.
EDIT
In my answer above i assume that the id's encountered are incremented values, but you don't say that so, if for example you encounter id=10
, and then encounter id=1
the above would still result in 10
in the file, to handle that just add some padding to the string that you're writing using str_pad:
str_pad($value_to_write, 10); //or whatever value is reasonable.
Upvotes: 1
Reputation: 78423
If you can, try memcache->increment().
http://php.net/manual/en/memcache.increment.php
Use $memcache->add('beer_id', 0);
to initialize it to zero. Then fetch $beer_id
like $memcache->get('beer_id')
for an initial sanity check, and then $memcache->increment('beer_id');
for the next $beer_id
.
Else, stick to file_get_contents()
and file_put_contents()
:
Upvotes: 1