As an alternative, consider writing the data to a temporary file first, in which case you can just write the new data first followed by the existing data. Then, if all goes well, (a) delete the .bak file, rename the original file to the .bak file, and rename the tmp file to the original name. (Note this does not preserve the file permissions on the original file, so beware if the permissions must be other than the default!)
In code (in real life you'd probably want to do something more graceful than die at the first sign of error!):
function insert_new_data( $new_data, $filename )
{
$tmp_filename = $filename . getmypid();
$ bak_filename = $filename . ".bak";
$tmpf = fopen($tmp_filename,"w") or die("Can't make tmp");
fwrite( $tmpf, $new_data );
$oldf = fopen( $filename, "r");
while (!feof($oldf))
{
$data = fgets($oldf, 65536);
fwrite( $tmpf, $data );
}
fclose ($oldf);
fclose ($tmpf);
unlink( $bak_filename );
rename( $filename, $bak_filename );
rename( $tmp_filename, $filename );
}
And what posting of mine would be complete without a warning that it's not multi-user safe? :-) If you do need to guard against this, you should have a separate file you use to lock, as the flock() call will not survive the file being
closed.