I have a directory with subfolders containing images. I need to display all these on one page, and also their folder name, so something like this:
echo Subfolder name
echo image, image, image
echo Subfolder2 name
echo image2, image2 , image2
I've tried using
$images = glob($directory . "*.jpg");
but the problem is I have to exactly define the subfolder name in $directory
, like "path/folder/subfolder/";
Is there any option like some "wildcard" that would check all subfolders and echo foreach
subfolder name and its content?
Also, opendir
and scandir
can't be applied here due to server restrictions I can't control.
Glob normally have a recursive wildcard, written like /**/, but PHP Glob function doesn't support it. So the only way is to write a your own function. Here's a simple one that support recursive wildcard:
<?php
function recursiveGlob($pattern)
{
$subPatterns = explode('/**/', $pattern);
// Get sub dirs
$dirs = glob(array_shift($subPatterns) . '/*', GLOB_ONLYDIR);
// Get files in the current dir
$files = glob($pattern);
foreach ($dirs as $dir) {
$subDirList = recursiveGlob($dir . '/**/' . implode('/**/', $subPatterns));
$files = array_merge($files, $subDirList);
}
return $files;
}
Use it like that $files = recursiveGlob("mainDir/**/*.jpg");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With