What are the best practices for handling file manipulation operations in PHP to ensure content is not lost?

When performing file manipulation operations in PHP, it is crucial to use error handling techniques to prevent content loss. One common practice is to first check if the file exists before attempting any operations on it. Additionally, using functions like file_put_contents() with the LOCK_EX flag can help prevent race conditions and ensure data integrity.

// Check if the file exists before performing any operations
if (file_exists('example.txt')) {
    // Use file_put_contents with LOCK_EX to prevent race conditions
    file_put_contents('example.txt', 'New content', LOCK_EX);
} else {
    echo 'File does not exist.';
}