What are best practices for handling file operations in PHP, such as opening, writing, and closing files, to avoid errors like connection failures or permission issues?

When handling file operations in PHP, it is important to properly handle errors such as connection failures or permission issues. One way to do this is by using try-catch blocks to catch exceptions that may occur during file operations. Additionally, it is recommended to check for file existence and permissions before attempting to open or write to a file.

try {
    $file = 'example.txt';
    
    if (!file_exists($file) || !is_writable($file)) {
        throw new Exception('File does not exist or is not writable');
    }
    
    $handle = fopen($file, 'w');
    
    if (!$handle) {
        throw new Exception('Failed to open file');
    }
    
    fwrite($handle, 'Hello, World!');
    
    fclose($handle);
    
    echo 'File written successfully';
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}