Forum Moderators: coopster

Message Too Old, No Replies

PHP Directory Search

         

andrewsmd

8:25 pm on Mar 17, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have a program that searches directories for a wild card. i.e. C:\some folder\*.txt would return any file with a .txt extension in the path C:\some folder. Let's say that these files are in c:\some folder

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,

rocknbil

9:18 pm on Mar 17, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



How *I* would approach this is
1. Build a list of directories
2. build the list of the main target directory
3. Loop through the directories for files and add them to that list.


// 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! :-)