Search code examples
phpfilesystems

How to loop and get data of all nested files and subfolders


I have a top folder named home and nested folders and files inside
I need to insert some data from files and folders into a table
The following (simplified) code works fine if I manually declare parent folder for each level separatelly, i.e. - home/lorem/, home/impsum/, home/ipsum/dolor/ etc
Is there a way to do this automatically for all nested files and folders ?
Actually, I need the path for each of them on each level

$folders = glob("home/*", GLOB_ONLYDIR);
foreach($folders as $el){
    //$path = ??;
    //do_something_with folder;
}
$files = glob("home/*.txt");
foreach($files as $el){
    //$path = ??;
    //do_something_with file;
}

Solution

  • PHP has the recursiveIterator suite of classes - of which the recursiveDirectoryIterator is the correct tool for the task at hand.

    # Where to start the recursive scan
    $dir=__DIR__;
    
    # utility
    function isDot( $dir ){
        return basename( $dir )=='.' or basename( $dir )=='..';
    }
    
    # create new instances of both recursive Iterators
    $dirItr=new RecursiveDirectoryIterator( $dir, RecursiveDirectoryIterator::KEY_AS_PATHNAME );
    $recItr=new RecursiveIteratorIterator( $dirItr, RecursiveIteratorIterator::CHILD_FIRST );
    
    foreach( $recItr as $obj => $info ) {
        
        # directories
        if( $info->isDir() && !isDot( $info->getPathname() ) ){
            printf('> Folder=%s<br />',realpath( $info->getPathname() ) );
        }
        
        # files
        if( $info->isFile() ){
            printf('File=%s<br />',$info->getFileName() );
        }
    }