What are some best practices for handling file writing in PHP?

When handling file writing in PHP, it is important to ensure proper error handling, permissions, and file locking to prevent data corruption or loss. It is recommended to use functions like fopen(), fwrite(), and fclose() to open, write, and close files respectively. Additionally, consider using file locking mechanisms like flock() to prevent concurrent writes to the same file.

// Open a file for writing
$filename = 'example.txt';
$file = fopen($filename, 'w');

if ($file) {
    // Write data to the file
    fwrite($file, 'Hello, World!');

    // Close the file
    fclose($file);
} else {
    echo 'Unable to open file for writing.';
}