Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing all the folders subfolders and files in a directory using php

Tags:

directory

php

Please give me a solution for listing all the folders,subfolders,files in a directory using php. My folder structure is like this:

Main Dir  Dir1   SubDir1    File1    File2   SubDir2    File3    File4  Dir2   SubDir3    File5    File6   SubDir4    File7    File8 

I want to get the list of all the files inside each folder.

Is there any shell script command in php?

like image 738
Warrior Avatar asked Aug 19 '11 12:08

Warrior


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 The scandir function is an inbuilt function that returns an array of files and directories of a specific directory. It lists the files and directories present inside the path specified by the user.

How do I get a list of all folders and subfolders?

Substitute dir /A:D. /B /S > FolderList. txt to produce a list of all folders and all subfolders of the directory. WARNING: This can take a while if you have a large directory.

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

The scandir() function in PHP is an inbuilt function that 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

function listFolderFiles($dir){     $ffs = scandir($dir);      unset($ffs[array_search('.', $ffs, true)]);     unset($ffs[array_search('..', $ffs, true)]);      // prevent empty ordered elements     if (count($ffs) < 1)         return;      echo '<ol>';     foreach($ffs as $ff){         echo '<li>'.$ff;         if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);         echo '</li>';     }     echo '</ol>'; }  listFolderFiles('Main Dir'); 
like image 167
Shef Avatar answered Sep 24 '22 03:09

Shef


A very simple way to show folder structure makes use of RecursiveTreeIterator class (PHP 5 >= 5.3.0, PHP 7) and generates an ASCII graphic tree.

$it = new RecursiveTreeIterator(new RecursiveDirectoryIterator("/path/to/dir", RecursiveDirectoryIterator::SKIP_DOTS)); foreach($it as $path) {   echo $path."<br>"; } 

http://php.net/manual/en/class.recursivetreeiterator.php

There is also some control over the ASCII representation of the tree by changing the prefixes using RecursiveTreeIterator::setPrefixPart, for example $it->setPrefixPart(RecursiveTreeIterator::PREFIX_LEFT, "|");

like image 31
jim_kastrin Avatar answered Sep 23 '22 03:09

jim_kastrin