Jump to content

[SOLVED] Recursive Folder Reading


Bricktop

Recommended Posts

Hi all,

 

I have the following code which reads the files in a given directory and outputs the filenames to an array.  It works great but I wonder if anyone can tell me how to amend it so it can also look through subdirectories.

 

Basically I would like subdirectories to be held in an array, and the the files contained within those subdirectories to be held in an array inside the relevant subdomain array (if that makes sense?)

 

So, basically I could do:

 

foreach($subdirectory)
{
echo $subdirectoryname;
    foreach($filename)
    {
    echo $filename;
    }

}

 

Anyway, here's my current code:

 

// create an array to hold directory list
    $results = array();

    // create a handler for the directory
    $handler = opendir('backups/');

    // keep going until all files in directory have been read
    while ($file = readdir($handler)) {

        // if $file isn't this directory or its parent, 
        // add it to the results array
        if ($file != '.' && $file != '..')
            $results[] = $file;
    }

    // tidy up: close the handler
    closedir($handler);

 

Any ideas welcome!

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/173393-solved-recursive-folder-reading/
Share on other sites

Maybe make an array of files and folders with scandir and then run through your array with the isdir function on each? If isdir() returns true, you can opendir() that directory, and when isdir() returns false on the entire scandir() array, you can go up one folder and start where you left off.

 

I'm not sure. That almost sounds too complicated...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.