What are the best practices for handling file operations in PHP to ensure proper functionality and error handling?

When handling file operations in PHP, it is important to ensure proper functionality and error handling to prevent issues such as file corruption or data loss. One best practice is to always check if a file exists before performing any operations on it, and handle errors gracefully using try-catch blocks.

// Check if file exists before performing any operations
$file = 'example.txt';

if (file_exists($file)) {
    // Perform file operations here
    try {
        // Open the file for reading
        $handle = fopen($file, 'r');
        
        // Read the contents of the file
        $contents = fread($handle, filesize($file));
        
        // Close the file
        fclose($handle);
        
        // Output the contents
        echo $contents;
    } catch (Exception $e) {
        // Handle any errors
        echo 'Error: ' . $e->getMessage();
    }
} else {
    echo 'File does not exist.';
}