What are the best practices for handling file operations in PHP, specifically when writing to a file?

When writing to a file in PHP, it is important to handle file operations carefully to avoid data loss or corruption. It is recommended to use file locking to prevent multiple processes from writing to the file simultaneously, and to properly handle errors that may occur during the writing process.

$filename = 'example.txt';
$file = fopen($filename, 'a'); // Open the file in append mode

if (flock($file, LOCK_EX)) { // Lock the file for exclusive writing
    fwrite($file, 'Hello, world!'); // Write data to the file
    flock($file, LOCK_UN); // Unlock the file
} else {
    echo 'Unable to acquire lock on file.';
}

fclose($file); // Close the file