What is the best way to recursively read and output the contents of a directory with PHP?

To recursively read and output the contents of a directory with PHP, you can use a recursive function that iterates through each item in the directory. This function should check if the item is a file or a directory, and if it's a directory, call itself recursively to read its contents. Finally, output the file names or directory names as needed.

function readDirectory($dir){
    $files = scandir($dir);
    
    foreach($files as $file){
        if($file != '.' && $file != '..'){
            if(is_dir($dir.'/'.$file)){
                echo 'Directory: '.$file.'<br>';
                readDirectory($dir.'/'.$file);
            } else {
                echo 'File: '.$file.'<br>';
            }
        }
    }
}

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