What are the potential challenges of recursively reading a directory in PHP, including handling links?

When recursively reading a directory in PHP, one potential challenge is handling symbolic links. If not properly handled, symbolic links can cause infinite loops or duplicate entries in the directory traversal. To solve this issue, you can keep track of visited directories and skip symbolic links during the traversal process.

function readDirectory($dir, &$files = array()){
    $dir = rtrim($dir, '/');
    $dh = opendir($dir);
    
    if(!$dh) {
        return false;
    }
    
    while (($file = readdir($dh)) !== false) {
        if($file == '.' || $file == '..') {
            continue;
        }
        
        $path = $dir . '/' . $file;
        
        if(is_link($path)) {
            continue;
        }
        
        if(is_dir($path)) {
            readDirectory($path, $files);
        } else {
            $files[] = $path;
        }
    }
    
    closedir($dh);
    
    return $files;
}

$directory = 'path/to/directory';
$files = readDirectory($directory);

print_r($files);