What are some best practices for reading directories and subdirectories in PHP and displaying them as links?

When reading directories and subdirectories in PHP, it is important to recursively scan through each directory to retrieve all files and folders. Once the directories are scanned, you can display them as links on a webpage by iterating through the results and creating HTML anchor tags for each item.

<?php
function displayDirectory($dir){
    if(is_dir($dir)){
        $files = scandir($dir);
        
        foreach($files as $file){
            if($file != '.' && $file != '..'){
                if(is_dir($dir.'/'.$file)){
                    echo '<a href="'.$dir.'/'.$file.'">'.$file.'</a><br>';
                    displayDirectory($dir.'/'.$file);
                } else {
                    echo '<a href="'.$dir.'/'.$file.'">'.$file.'</a><br>';
                }
            }
        }
    }
}

$directory = 'path/to/your/directory';
displayDirectory($directory);
?>