Skip to content
PHP Logo

What is the potential issue with the while loop in the PHP code when scanning directories?

The potential issue with the while loop in the PHP code when scanning directories is that it may lead to an infinite loop if not properly controlled. To solve this issue, you can add a condition to break out of the loop when there are no more files or directories to scan.

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

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            // Skip current and parent directory entries
            if ($file == '.' || $file == '..') {
                continue;
            }
            
            // Process the file or directory
            echo $file . "<br>";
        }
        closedir($dh);
    }
}