What is the correct file mode to use in PHP fopen to append data at the beginning of a file?

When using PHP fopen to append data at the beginning of a file, the correct file mode to use is "r+". This file mode allows you to read and write to the file without truncating it. By using this file mode, you can position the file pointer at the beginning of the file and write data without overwriting existing content.

$file = 'example.txt';
$data = "New data to append at the beginning of the file\n";

$handle = fopen($file, 'r+');
$existingData = fread($handle, filesize($file));
rewind($handle);
fwrite($handle, $data . $existingData);

fclose($handle);