Scandir only show folders, not files

I have some PHP used to pull a list of files from my image directory - it is used in the form to select where the downloaded image will be uploaded. Below is the code:

$files = array_map("htmlspecialchars", scandir("../images")); foreach ($files as $file) { $filelist .= sprintf('<option value="%s">%s</option>' . PHP_EOL, $file, $file ); } 

It works fine, but it shows all the files and folders in the "images", someone knows a way to change this code so that it only displays the names of the folders found in the "images" folder, and not any other files.

thanks

+7
php
source share
3 answers

The simplest and fastest will be glob with the GLOB_ONLYDIR flag:

 foreach(glob('../images/*', GLOB_ONLYDIR) as $dir) { $dirname = basename($dir); } 
+15
source share

The is_dir() function is the solution:

 foreach ($files as $file) { if(is_dir($file) and $file != "." && $file != "..") $filelist .= sprintf('<option value="%s">%s</option>' . PHP_EOL, $file, $file ); } 
+5
source share

The is_dir () function requires an absolute path to the item being checked.

 $base_dir = get_home_path() . '/downloads'; //get_home_path() is a wordpress function $sub_dirs = array(); $dir_to_check = scandir($dir); foreach ($dir_to_check as $item){ if ($item != '..' && $item != '.' && is_dir($base_dir . "/" . $item)){ array_push($sub_dirs, $item); } } 
+4
source share

All Articles