Are there any best practices for efficiently adding content to a file in PHP without overwriting existing data?

When adding content to a file in PHP without overwriting existing data, one common approach is to open the file in "append" mode instead of "write" mode. This allows new data to be added at the end of the file without affecting the existing content. Additionally, it's important to properly handle file locking to prevent conflicts when multiple processes are trying to write to the same file simultaneously.

$file = 'example.txt';
$data = "New content to add to the file";

$handle = fopen($file, 'a');
if ($handle === false) {
    die("Unable to open file for appending");
}

if (flock($handle, LOCK_EX)) {
    fwrite($handle, $data . PHP_EOL);
    flock($handle, LOCK_UN);
} else {
    echo "Couldn't get the lock!";
}

fclose($handle);