Are there any best practices for handling file operations within IF statements in PHP?

When handling file operations within IF statements in PHP, it is important to check if the file exists before attempting any operations on it. This helps prevent errors and ensures that the file is available for manipulation. Additionally, it is good practice to close the file handle after performing the necessary operations to free up system resources.

$filename = 'example.txt';

if (file_exists($filename)) {
    $file = fopen($filename, 'r');
    
    // Perform file operations here
    
    fclose($file);
} else {
    echo "File does not exist.";
}