What are the best practices for handling file streams in PHP to avoid errors like "supplied argument is not a valid stream resource"?

The error "supplied argument is not a valid stream resource" occurs when a function that expects a valid file stream resource is given an invalid or closed stream. To avoid this error, always check if the file stream is valid before using it in any file-related functions.

$file = fopen('example.txt', 'r');

if ($file) {
    // File stream is valid, perform file operations here
    fclose($file);
} else {
    // Handle error when file stream is not valid
    echo "Error opening file.";
}