What are best practices for handling file writing in PHP to prevent corruption?

When writing files in PHP, it is important to use file locking to prevent corruption when multiple processes try to write to the same file simultaneously. This can be achieved by using the `flock()` function before writing to the file. Additionally, it is recommended to use error handling to catch any potential issues that may arise during the file writing process.

$file = 'example.txt';

$handle = fopen($file, 'a');
if (flock($handle, LOCK_EX)) {
    fwrite($handle, 'Hello, World!');
    flock($handle, LOCK_UN);
} else {
    echo 'Could not lock file.';
}

fclose($handle);