How can one effectively debug and handle errors related to file handling functions in PHP, such as fopen() and fgets()?

When dealing with file handling functions in PHP, such as fopen() and fgets(), it's important to handle errors effectively to prevent unexpected behavior or crashes in your application. To debug and handle errors related to file handling functions, you can use error handling functions like try-catch blocks or checking for errors using functions like feof() or file_exists(). Additionally, make sure to check for file permissions, file existence, and proper file paths to avoid errors.

<?php

$filename = "example.txt";

try {
    $file = fopen($filename, "r");
    
    if (!$file) {
        throw new Exception("Unable to open file.");
    }

    while ($line = fgets($file)) {
        echo $line;
    }

    fclose($file);
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

?>