Forum Moderators: coopster
test.txt
test2.txt
folder1 (a folder)
folder2 (another folder)
Now I would like to be able to realize that folder1 and 2 are folders and then in turn search within them. I would like to repeat that for any folders within them and so on. Here is the code I have so far
//an array of the results
$arrayReturn = array();
//an array of the files
$input = glob("c:\\some folder\\*.txt");
foreach($input as $i){
//if it is a folder
if(is_dir($i)){
//we have a directory and I need to search it again.
//i don't know what to do here
}//if
//else it is a file
else{
array_push($returnArray, $i);
}
}//foreach
How would I keep going on and then searching folders within itself. Does this require some kind of recursion? Thanks,
// Or make $filetypes a scalar, in which case you can
// eliminate the foreach on $filetypes
$filetypes = Array('*.txt');
$arrayReturn = Array();
$directories = Array();
//The target directory.
$targetDirectory ="c:\\some-folder";
if ($handle = opendir($targetDirectory)) {
while (false !== ($file = readdir($handle))) {
if(is_dir($file)){ array_push($directories,$file); }
else {
foreach ($filetypes as $type) {
if (preg_match("/$type$/i",$file)) { array_push($arrayReturn,$file); }
}
}
}
closedir($handle);
}
// If there's no directories, this does nothing
foreach($directories as $dir){
if ($handle = opendir("$targetDirectory\\$dir")) {
while (false !== ($file = readdir($handle))) {
foreach ($filetypes as $type) {
if (preg_match("/$type$/i",$file)) { array_push($arrayReturn,"$dir\\$file"); }
}
}
closedir($handle);
}
}
header("Content-type:text/html\n\n");
print "<ul>\n";
foreach ($arrayReturn as $file) { print "<li>$file </li>\n"; }
print "</ul>\n";
// or var_dump($arrayReturn)
So your potential list would be
file1.txt
file2.txt
folder1/file1.txt
folder1/file2.txt
folder2/file1.txt
folder2/file2.txt
WARNING: Untested, you debug it! :-)