What best practices should be followed when working with file operations in PHP to avoid data duplication or loss?

To avoid data duplication or loss when working with file operations in PHP, it is important to check for the existence of the file before creating or writing to it. Additionally, using file locking mechanisms can prevent multiple processes from accessing and modifying the same file simultaneously, reducing the risk of data corruption. Regularly backing up files and implementing error handling to catch and handle any exceptions that may occur during file operations is also crucial.

$filename = 'example.txt';

if (!file_exists($filename)) {
    $file = fopen($filename, 'w');
    fwrite($file, 'Initial content');
    fclose($file);
}

$file = fopen($filename, 'a');
flock($file, LOCK_EX);

// Perform file operations here

flock($file, LOCK_UN);
fclose($file);