What are some best practices for handling file operations in PHP, such as fopen() and fclose() functions?

When working with file operations in PHP, it is important to always properly handle opening and closing files to prevent memory leaks and ensure data integrity. Best practices include using the fopen() function to open a file for reading or writing, performing operations on the file, and then closing the file using the fclose() function to release system resources.

// Example of opening a file, writing to it, and closing it
$filename = "example.txt";
$file = fopen($filename, "w");

if ($file) {
    fwrite($file, "Hello, World!");
    fclose($file);
} else {
    echo "Error opening file.";
}