简体   繁体   中英

scandir to only show folders, not files

I have a bit of PHP used to pulled a list of files from my image directory - it's used in a form to select where an uploaded image will be saved. 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 shows all files and folders in 'images', does someone know a way to modify this code so that it only shows folder names found in the 'images' folder, not any other files.

Thanks

The easiest and quickest will be glob with GLOB_ONLYDIR flag:

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

Function is_dir() 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 );

}

The is_dir() function requires an absolute path to the item that it is checking.

$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);
  }
}

You could just use your array_map function combined with glob

$folders = array_map(function($dir) {
    return basename($dir);
}, glob('../images/*', GLOB_ONLYDIR));

Yes, I copied a part of it of dev-null-dweller , but I find my solution a bit more re-useable.

I try this

    <?php

$dir = "../";

$a = array_map("htmlspecialchars", scandir($dir));

$no = 0; foreach ($a as $file) {

  if ( strpos($file, ".") == null && $file !== "." && $file !== ".." ) {
    $filelist[$no] = $file; $no ++;
  }

}
print_r($filelist);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM