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

When handling file operations in PHP, it is important to follow best practices to ensure security, efficiency, and reliability. This includes using proper file permissions, validating user input, sanitizing file paths, checking for errors, and properly closing file handles after use.

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

// Define the file path
$file_path = '/path/to/file.txt';

// Check if the file exists and is readable
if (file_exists($file_path) && is_readable($file_path)) {
    // Open the file for reading
    $file_handle = fopen($file_path, 'r');

    // Check if file handle was successfully created
    if ($file_handle) {
        // Read the file contents
        $file_contents = fread($file_handle, filesize($file_path));

        // Close the file handle
        fclose($file_handle);

        // Output the file contents
        echo $file_contents;
    } else {
        echo 'Error opening file.';
    }
} else {
    echo 'File does not exist or is not readable.';
}