What are the best practices for handling file paths and directory structures in PHP scripts to avoid errors like "Warning: readdir(): supplied argument is not a valid Directory resource"?

When working with file paths and directory structures in PHP scripts, it is important to ensure that the directory being accessed is valid before attempting to read from it using functions like `readdir()`. To avoid errors like "Warning: readdir(): supplied argument is not a valid Directory resource", you should first check if the directory handle is valid using `is_resource()` or `is_dir()`. This will help prevent the script from attempting to read from an invalid directory.

$directory = 'path/to/directory';

if (is_dir($directory)) {
    $dir_handle = opendir($directory);

    while (false !== ($file = readdir($dir_handle))) {
        // Process files in the directory
    }

    closedir($dir_handle);
} else {
    echo "Invalid directory path";
}