What are some common pitfalls or errors that can occur when using fopen in PHP, as demonstrated in the provided code snippet?

One common pitfall when using fopen in PHP is not checking if the file was successfully opened before attempting to read from or write to it. This can lead to errors if the file doesn't exist or if there are permission issues. To solve this, always check the return value of fopen to ensure the file was opened successfully before proceeding with any file operations.

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

if ($handle) {
    // File opened successfully, proceed with operations
    while (($line = fgets($handle)) !== false) {
        echo $line;
    }

    fclose($handle);
} else {
    echo "Unable to open file $file";
}