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;
}
CodePudding user response:
I would suggest you to use The Finder Component
use Symfony\Component\Finder\Finder;
$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();
}
CodePudding user response:
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() );
}
}