What are best practices for handling errors returned by scandir in PHP?

When using scandir in PHP to read the contents of a directory, it's important to handle any potential errors that may occur during the process. One common error is when the specified directory does not exist or is not readable, which can result in scandir returning false. To handle this error, you can check the return value of scandir and display an appropriate message to the user.

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

if (is_dir($directory)) {
    $files = scandir($directory);
    
    if ($files !== false) {
        // Process the files
    } else {
        echo 'Error reading directory.';
    }
} else {
    echo 'Directory does not exist or is not readable.';
}