PHP List Directory structure and exclude some directories
php
Solution
In essence, my answer is not much different from Thomas' answer. However, he does not get a few things correct:
- The semantics correct for the `RecursiveCallbackFilterIterator` require you to return `true` to recurse into subdirectories.
- He doesn't skip the `.` and `..` directories inside each sub-directory
- His `in_array` check doesn't quite do what he expects
So, I wrote this answer instead. This will work correctly, assuming I understand what you want:
Edit: He has since fixed 2 of those three issues; the third may not be an issue because of the way he wrote his conditional check but I am not quite sure.
<?php
$directory = '../admin';
// Will exclude everything under these directories
$exclude = array('.git', 'otherDirToExclude');
/**
* @param SplFileInfo $file
* @param mixed $key
* @param RecursiveCallbackFilterIterator $iterator
* @return bool True if you need to recurse or if the item is acceptable
*/
$filter = function ($file, $key, $iterator) use ($exclude) {
if ($iterator->hasChildren() && !in_array($file->getFilename(), $exclude)) {
return true;
}
return $file->isFile();
};
$innerIterator = new RecursiveDirectoryIterator(
$directory,
RecursiveDirectoryIterator::SKIP_DOTS
);
$iterator = new RecursiveIteratorIterator(
new RecursiveCallbackFilterIterator($innerIterator, $filter)
);
foreach ($iterator as $pathname => $fileInfo) {
// do your insertion here
}
Problem
I have this PHP Code: ``` $rootpath = '../admin/'; $inner = new RecursiveDirectoryIterator($rootpath); $fileinfos = new RecursiveIteratorIterator($inner); foreach ($fileinfos as $pathname => $fileinfo) { $pathname2 = substr($pathname,2); $sql = "SELECT * from admin_permissions where page_name = '$pathname2'"; $rs = mysql_query($sql,$conn); if (mysql_num_rows($rs) == 0) { if (!$fileinfo->isFile()) continue; $sql2 = "INSERT into admin_permissions (page_name) values ('$pathname2')"; $rs2 = mysql_query($sql2,$conn); echo "$pathname<br>"; } } ``` That is displaying my directory structure and inserting the directories and file names into a database (removing the first 2 characters `..`). Since the `RecursiveDirectoryIterator` iterates through all files in all directories, how can I exclude whole directories, including all files within them?