What are common pitfalls when using fopen in PHP to access files?

Common pitfalls when using fopen in PHP include not checking if the file exists before opening it, not handling errors properly, and not closing the file after use. To avoid these pitfalls, always check if the file exists, handle errors using try-catch blocks, and close the file using fclose() after reading or writing to it.

$file = "example.txt";

try {
    if (file_exists($file)) {
        $handle = fopen($file, "r");
        // Read from or write to the file here
        fclose($handle);
    } else {
        throw new Exception("File does not exist");
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}