What potential pitfalls can arise when using loops in PHP to iterate through directories and files?

One potential pitfall when using loops in PHP to iterate through directories and files is the possibility of encountering infinite loops if the loop conditions are not properly defined. To avoid this, it is important to set clear exit conditions within the loop to prevent it from running indefinitely.

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

if ($handle = opendir($dir)) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            // Process files or subdirectories here
        }
    }
    closedir($handle);
}