What are the best practices for handling file writing operations in PHP to avoid unexpected errors or data corruption?

When handling file writing operations in PHP, it is important to ensure proper error handling, permissions, and data validation to avoid unexpected errors or data corruption. To do this, always check if the file can be opened for writing, handle errors gracefully, sanitize user input, and consider using file locking to prevent concurrent writes.

<?php
$filename = 'example.txt';

// Check if file can be opened for writing
if ($file = fopen($filename, 'w')) {
    // Write data to file
    fwrite($file, 'Hello, World!');
    fclose($file);
    echo 'File written successfully.';
} else {
    echo 'Error opening file for writing.';
}
?>