What are the potential pitfalls of using fopen to read a file in PHP and how can they be avoided?

One potential pitfall of using fopen to read a file in PHP is not checking if the file actually exists before attempting to open it. This can lead to errors or unexpected behavior in your script. To avoid this issue, you should use the file_exists function to check if the file exists before trying to open it with fopen.

$file = 'example.txt';

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