1

I have 4 folders that I want to check the images and php files in it. here is the structural folder arrangement.

The main_folder contains two sub-folder (second_folder and third_folder) while the third_folder contains a sub-folder (fourth_folder) and so on.

Currently with the code below, I can only access all the files in first_main_folder.

$files = glob('first_Main_folder/*.{jpg,png,gif,php}', GLOB_BRACE);
foreach($files as $file) {
echo "<br>$file<br>";
}

Please how do I access files in the remaining subfolders (second_folder, third_folder, fourth_folder) and so on

Thanks

first_Main_folder
test.png
data.php
check.gif


    second_folder
    tony.jpg
    mark.gif
    action.php

    third_folder
    index.php
    post.php
    sender.php
    han.gif

        fourth_folder
            catch.php
            index2.php
            redirect.php

       and so on 
jmarkatti
  • 621
  • 8
  • 29

2 Answers2

0

This function below scan both main and all sub-directory to the very end. It works for me. thanks.

function outputFiles1($path){
    // Check directory exists or not
    if(file_exists($path) && is_dir($path)){
        // Search the files in this directory
        $files = glob($path ."/*");
        if(count($files) > 0){
            // Loop through retuned array
            foreach($files as $file){
                if(is_file("$file")){
                    // Display only filename
                    echo basename($file) . filesize($file) . "<br>";
                } else if(is_dir("$file")){
                    // Recursively call the function if directories found
                    outputFiles1("$file");
                }
            }
        } else{
            echo "ERROR: No such file found in the directory.";
        }
    } else {
        echo "ERROR: The directory does not exist.";
    }
}

// Call the function
outputFiles1("C:/xampp/htdocs/first_main_folder");
jmarkatti
  • 621
  • 8
  • 29
0

The following example was taken from this post.

function rsearch($folder, $pattern='/.*/') {
    $dir = new RecursiveDirectoryIterator($folder);
    $ite = new RecursiveIteratorIterator($dir);

    $files = new RegexIterator($ite, $pattern, RegexIterator::GET_MATCH);
    $fileList = array();

    foreach($files as $file) {
        $fileList = array_merge($fileList, $file);
    }
    return $fileList;
}


$result = rsearch('./');
print_r($result);
Bram Verstraten
  • 1,414
  • 11
  • 24
  • 1
    My solution already answered the question but it seems your own solution is also good so am accepting as the answer – jmarkatti Jul 18 '19 at 19:10