What are the potential pitfalls of not properly checking for the existence of a directory in PHP?

If you do not properly check for the existence of a directory in PHP before attempting to perform operations on it, you may encounter errors such as "Directory not found" or "Permission denied." To avoid these pitfalls, you should always check if the directory exists before proceeding with any file operations.

$directory = '/path/to/directory';

if (is_dir($directory)) {
    // Directory exists, proceed with operations
    // For example, listing files in the directory
    $files = scandir($directory);
    foreach ($files as $file) {
        echo $file . "<br>";
    }
} else {
    echo "Directory does not exist.";
}