John K
John K

Reputation: 105

PHP echo all subfolder images

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:

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.

Upvotes: 6

Views: 1074

Answers (1)

Jarzon
Jarzon

Reputation: 652

Glob normally have a recursive wildcard, written like /**/, but PHP Glob function doesn't support it. So the only way is to write 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");

Upvotes: 3

Related Questions