PHP parses directory and subdirectories for file paths and names of jpg image types only

I want to modify this PHP code to do a recursive search and display of an image in one known directory with an unknown number of subdirectories.

Here is the code I have that scans a single directory and iterates over files in html:

<?php 
    foreach(glob('./img/*.jpg') as $filename)
    {
        echo '<img src="'.$filename.'"><br>';
    }
?>

Given that the base directory $base_dir="./img/";contains subdirectories with unknown amounts and levels of their own subdirectories, all of which include only .jpg files.

In principle, you need to build an array of all the subdirectory paths.

+3
source share
1 answer

. , ( ). , , .jpg.

function traverse_hierarchy($path)
{
    $return_array = array();
    $dir = opendir($path);
    while(($file = readdir($dir)) !== false)
    {
        if($file[0] == '.') continue;
        $fullpath = $path . '/' . $file;
        if(is_dir($fullpath))
            $return_array = array_merge($return_array, traverse_hierarchy($fullpath));
        else // your if goes here: if(substr($file, -3) == "jpg") or something like that
            $return_array[] = $fullpath;
    }
    return $return_array;
}
+5

Source: https://habr.com/ru/post/1734488/


All Articles