简体   繁体   中英

PHP Scan but exclude certain folders and files

I want to exclude some files and folders from listing in a path. I created the following code for this but it doesn't work. All files are still displayed. What could be the reason for this?

$directories = '/var/../';
$excludes = array(
    'files' => array('requirements.txt', '.gitignore'),
    'dirs' => array('.git', 'logs')
);
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($directories, FilesystemIterator::SKIP_DOTS),
    RecursiveIteratorIterator::SELF_FIRST
);
foreach ($files as $path => $file) {
    if (!in_array($file, $excludes['dirs'])) {
        if (!in_array($file, $excludes['files'])) {
            echo $file->getFileName() . '<br>';
        }
    }
}

The problem is that you`ll exclude only dir.git, but not the files like.git/some-file inside the.git folder

But you can write recursion without iterator to avoid difficult validation for each file.. Here we just`ll not go to files / dirs, that we do not like

<?php
function getDirContents($dir, &$excludes, &$results = array()) {
    $files = scandir($dir);

    foreach ($files as $key => $value) {
        $path = realpath($dir . DIRECTORY_SEPARATOR . $value);
        if (!is_dir($path)) {
            if (!in_array($value, $excludes['files'])) {
              $results[] = $path;
            }
        } else if ($value != "." && $value != "..") {
            
            if (!in_array($value, $excludes['dirs'])) {
              getDirContents($path, $excludes, $results);
              $results[] = $path;
            }
        }
    }

    return $results;
}

$directories = '/var/../';
$excludes = array(
  'files' => array('requirements.txt', '.gitignore'),
  'dirs' => array('.git', 'logs')
);
var_dump(getDirContents($directories, $excludes));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM