What are common pitfalls when using fopen to read file contents in PHP?

A common pitfall when using fopen to read file contents in PHP is not checking if the file exists before attempting to read from it. This can lead to errors or unexpected behavior if the file is not found. To solve this issue, you should always check if the file exists using the file_exists function before opening it with fopen.

$filename = 'example.txt';

if (file_exists($filename)) {
    $file = fopen($filename, 'r');
    
    // Read file contents here
    
    fclose($file);
} else {
    echo "File not found.";
}