Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

like image 879
John K Avatar asked Oct 30 '22 02:10

John K


1 Answers

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

like image 181
Jarzon Avatar answered Nov 15 '22 06:11

Jarzon