Php - glob to find directories and .jpg only
What if I only want to search subdirectories and some file types. Ex. I have a folder named "stuff" where random stuff is loaded. And I will say that I want to search only subfolders of AND.jpg files in "stuff" and nothing more. I know to look for only .jpg is ...
$array = glob(‘stuff/{*.jpg}’, GLOB_BRACE);
and searching only subdirectories is ...
$array = glob(‘stuff/*’, GLOB_ONLYDIR);
... but how can I combine these two without any other unwanted files? Is there a template for subdirectories for GLOB_BRACE?
This recursive function should do the trick:
function recursiveGlob($dir, $ext) {
$globFiles = glob("$dir/*.$ext");
$globDirs = glob("$dir/*", GLOB_ONLYDIR);
foreach ($globDirs as $dir) {
recursiveGlob($dir, $ext);
}
foreach ($globFiles as $file) {
print "$file\n"; // Replace '\n' with '<br />' if outputting to browser
}
}
Using: recursiveGlob('C:\Some\Dir', 'jpg');
If you want it to do other things for an individual file, just replace the print "$file\n"
.
The feature may be more specific in their searches glob
, and also only link directories as well as files with the specified file extension, but I did it this way for simplicity and transparency.
I'm not sure if I'm following exactly because with you you're looking for a specific file type, and with the other you're looking for subdirectories. These are completely different templates!
As said, the way to have an array containing all * .jpg files in stuff/
as well as subdirectories in stuff/
is to take your code one more step:
$jpg_array = glob('stuff/{*.jpg}', GLOB_BRACE);
$subdir_array = glob('stuff/*', GLOB_ONLYDIR);
// Combine arrays
$items = array_merge($jpg_array,$subdir_array);
// Do something with values
foreach($items as $item)
{
echo($item . "<br>");
}