Skip to content
Advertisement

get folders and files like in a file explorer

I’m confused about all the file system functions in php (glob, scandir, opendir…)
I simply want a list of folders and files – like in a file explorer
something like this:

$path = 'home';
$arr = content of $path;
foreach($arr as $el){
if($el is a folder){echo "<div class='folder'>$el</div>";}
elseif($el is a file){echo "<div class='file'>$el</div>";}
}

Any help?

Advertisement

Answer

One approach :

$path = 'home'; // setting path

# Find pathnames matching a pattern 
# pattern : "home/*"
# will match : home/dir1, home/file.jpg, etc.
# and it will return an array
$arr = glob($path."/*");
foreach($arr as $el){
if ( is_dir($el) ) {
        echo "<div class='folder'>" . basename($el) . "</div>";
    } else {
        echo "<div class='file'>" . basename($el) . "</div>";
    }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement