skip to Main Content

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;
}

2

Answers


  1. I would suggest you to use The Finder Component

    use SymfonyComponentFinderFinder;
    
    $finder = new Finder();
    // find all files in the home directory
    $finder->files()->in('home/*');
    
    // To output their path
    foreach ($finder as $file) {
        $path = $file->getRelativePathname();
    }
    
    Login or Signup to reply.
  2. 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() );
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search