Get the hierarchy of a directory with PHP

function dir_contents_recursive($dir) {
    // open handler for the directory
    $iter = new DirectoryIterator($dir);

    foreach( $iter as $item ) {
        // make sure you don't try to access the current dir or the parent
        if ($item != '.' && $item != '..') {
            if( $item->isDir() ) {
                // call the function on the folder
                dir_contents_recursive("$dir/$item");
            } else {
                // print files
                echo $dir . "https://stackoverflow.com/" .$item->getFilename() . "<br>";
            }
        }
    }
}

Leave a Comment