Question: PHP echo all subfolder images


PHP echo all subfolder images

Answers 1
Added at 2017-09-07 18:09

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
  • etc

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.

Answers to

PHP echo all subfolder images

nr: #1 dodano: 2017-09-07 19:09

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 does:

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");

Source Show
◀ Wstecz