Overwriting Text in a File When It's Already Open
<p>I have a file that I'm opening for writing, like this:</p>

<pre><code>if (!$idHandle = fopen($fileName, 'w')) {
        echo "Cannot open file ($fileName)";
        die();
    }
</code></pre>

<p>I then enter a loop where I'm incrementing a variable, <code>$beerId</code>, during each iteration. I want to save that variable to the file I have open, so I use the following code: </p>

<pre><code>if (fwrite($idHandle, $beerId) === FALSE) {
    echo "Cannot write to file ($fileName)";
    die();
    }
$beerId++;
</code></pre>

<p>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.</p>

<p>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. </p>
