You didn't actually test this method, did you? Here's what "a+" mode actually does (quoting right out of the manual):
'a+' - Open for reading and writing; place the file pointer at the end
of the file. If the file does not exist, attempt to create it.
In other words, everything you write is going to be appended to the existing content anyway.
In order to really "insert" a line in an existing text file, use "r+" mode, which allows reading and writing anywhere within the file:
$filename = "file.txt";
if ($fp = fopen( $filename, "r+" ))
{
flock( $fp, 2 );
$old_data = fread( $fp, filesize( $filename ) );
rewind( $fp ); // set current position back to beginning
fwrite( $fp, "This is a new line at the top\n" );
fwrite( $fp, $old_data );
flock( $fp, 3 );
fclose( $fp );
}
Note this only works if the new contents are longer than the old contents. (Otherwise there would be some leftover garbage after the end of the last line.)