What are the best practices for handling file operations in PHP scripts?

When handling file operations in PHP scripts, it is important to follow best practices to ensure security, efficiency, and reliability. This includes validating user input, using absolute file paths, checking for file existence before performing operations, handling errors gracefully, and closing file resources properly after use.

// Example of best practices for handling file operations in PHP scripts

// Validate user input
$file = 'example.txt'; // Assume this is user input
if (preg_match('/^[a-zA-Z0-9_\-\.]+/', $file)) {
    // Use absolute file paths
    $filepath = '/path/to/files/' . $file;
    
    // Check for file existence
    if (file_exists($filepath)) {
        // Perform file operations
        $content = file_get_contents($filepath);
        
        // Handle errors gracefully
        if ($content === false) {
            echo 'Error reading file';
        } else {
            echo $content;
        }
        
        // Close file resource
        fclose($file);
    } else {
        echo 'File does not exist';
    }
} else {
    echo 'Invalid file name';
}