What best practices should be followed when using the readdir function in PHP to iterate through directory contents?

When using the readdir function in PHP to iterate through directory contents, it is important to properly handle the return values and use a while loop to iterate through all the files in the directory. Additionally, it is recommended to use the is_dir function to check if the current item is a directory before further processing it.

$dir = "/path/to/directory";

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if ($file != "." && $file != "..") {
                if (is_dir($dir . "/" . $file)) {
                    // Handle directory
                } else {
                    // Handle file
                }
            }
        }
        closedir($dh);
    }
}