What potential pitfalls can arise when using the readdir function in PHP?

One potential pitfall when using the readdir function in PHP is that it may return false when there are no more files in the directory, which can lead to an infinite loop if not handled properly. To solve this issue, you should check the return value of readdir and exit the loop when it returns false.

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

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if ($file != '.' && $file != '..') {
                // Process the file
            }
        }
        closedir($dh);
    }
}