What potential pitfalls should be avoided when using the opendir function in PHP to read files from a directory?

One potential pitfall when using the opendir function in PHP is not properly handling the returned resource and closing it after use. This can lead to resource leaks and potential performance issues. To avoid this, always remember to close the directory handle using closedir() after reading the files.

$dir = '/path/to/directory';
$handle = opendir($dir);

if ($handle) {
    while (false !== ($file = readdir($handle))) {
        // process file
    }
    
    closedir($handle);
} else {
    echo "Could not open directory.";
}