What are best practices for handling file operations in PHP, specifically when it comes to opening, writing, and closing files?

When handling file operations in PHP, it is important to properly open, write to, and close files to avoid potential issues like file corruption or resource leaks. To ensure proper file handling, always check for errors when opening files, write data securely, and close files after operations are completed.

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

// Open file for writing
$handle = fopen($filename, 'w');

if ($handle === false) {
    die('Could not open file for writing');
}

// Write data to file
$data = "Hello, World!";
fwrite($handle, $data);

// Close file
fclose($handle);
?>