Browse directory recursively and get filename
2 answers
Since I had to create the same functionality for my site, I will post my function as a link.
function recursiveFileSearch($path, $searchmask = "*") {
$path = rtrim($path, '/');
$files = array();
if(is_array($searchmask)) {
for($i = 0; $i < count($searchmask); $i++) {
$files = array_merge($files, glob($path.'/'.$searchmask[$i]));
}
sort($files);
} else {
$files = glob($path.'/'.$searchmask);
}
$dirs = glob($path.'/*', GLOB_ONLYDIR);
foreach($dirs as $dir) {
if(is_dir($dir)) {
$files = array_merge($files, recursiveFileSearch($dir, $searchmask));
}
}
sort($files);
return $files;
}
+3
source to share
I'm not 100% sure what you are asking, but if you look at the scandir documentation , the first comment has a very useful recursive scan function.
<?php
function dirToArray($dir) {
$result = array();
$cdir = scandir($dir);
foreach ($cdir as $key => $value)
{
if (!in_array($value,array(".","..")))
{
if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
{
$result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
}
else
{
$result[] = $value;
}
}
}
return $result;
}
?>
The results will be in the following format.
Array
(
[subdir1] => Array
(
[0] => file1.txt
[subsubdir] => Array
(
[0] => file2.txt
[1] => file3.txt
)
)
[subdir2] => Array
(
[0] => file4.txt
}
)
+2
source to share