What are some best practices for handling file writing operations in PHP to avoid data loss or corruption?

When writing files in PHP, it is important to handle errors and exceptions properly to avoid data loss or corruption. One best practice is to use file locking to prevent simultaneous writes from multiple processes. Additionally, always check for write permissions before attempting to write to a file.

$filename = 'example.txt';

// Check if file is writable
if (is_writable($filename)) {
    // Acquire an exclusive lock
    $file = fopen($filename, 'a');
    if (flock($file, LOCK_EX)) {
        fwrite($file, 'Hello, World!');
        flock($file, LOCK_UN); // Release the lock
    } else {
        echo "Couldn't get the lock!";
    }
    fclose($file);
} else {
    echo "File is not writable!";
}