Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scandir to only show folders, not files

Tags:

php

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

like image 608
user2574794 Avatar asked Sep 09 '13 19:09

user2574794


People also ask

How can I get a list of all the subfolders and files present in a directory using PHP?

PHP using scandir() to find folders in a directory To check if a folder or a file is in use, the function is_dir() or is_file() can be used. The scandir function is an inbuilt function that returns an array of files and directories of a specific directory.

How do I view a directory in PHP?

PHP scandir() Function$b = scandir($dir,1);

What is __ DIR __ in PHP?

The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.

How do I get a list of files in a directory in PHP?

you can esay and simply get list of file in folder in php. The scandir() function in PHP is an inbuilt function which is used to return an array of files and directories of the specified directory. The scandir() function lists the files and directories which are present inside a specified path.


2 Answers

The easiest and quickest will be glob with GLOB_ONLYDIR flag:

foreach(glob('../images/*', GLOB_ONLYDIR) as $dir) {
    $dirname = basename($dir);
}
like image 121
dev-null-dweller Avatar answered Oct 04 '22 16:10

dev-null-dweller


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

}
like image 23
Charaf JRA Avatar answered Oct 04 '22 15:10

Charaf JRA