What is the best practice for appending data to the beginning of a text file in PHP?

When appending data to the beginning of a text file in PHP, the best practice is to read the existing content of the file, prepend the new data to it, and then write the updated content back to the file. This ensures that the new data is added at the beginning without overwriting the existing content.

$file = 'example.txt';
$newData = "New data to append\n";

// Read the existing content of the file
$existingData = file_get_contents($file);

// Prepend the new data to the existing content
$updatedData = $newData . $existingData;

// Write the updated content back to the file
file_put_contents($file, $updatedData);