OK, time to reinvent my own wheel :-) ( frodo -- see below )
But first, the script you posted has one obvious error:
fwrite($fp, $data);
Clearly, this should refer to $data[$i]--i.e. an individual element of the array.
But the problem with the above is that there's no locking, so two or more instances could be trying to do this at the same time.
If I recall correctly, here's what I did before (warning--omits most error checking!):
$filename = 'somefile.txt';
$fp = fopen( $filename, 'r+' );
flock( $fp, 2 );
for ($i = 0; $data[$i] = fgets( $fp, 65000 ); $i++ )
{
}
rewind( $fp );
fwrite( $fp, "$newdata\n");
for ($i = 0; $i < sizeof($data); $i++ )
{
fwrite( $fp, $data[$i] . '\n' );
}
flock( $fp, 3 );
fclose($fp);
Note this only works with inserts: if you try to use it to delete a line from a text file, you'll end up with extra text at the end, measuring the exact length of the line that was deleted.
Now, here's a unique, arbitrary keyword that I can use to search for this posting in the future: frodo (I also put this in the top in case the keyword indexing only does the first N lines.)