Home > Software engineering >  PHP Scan but exclude certain folders and files
PHP Scan but exclude certain folders and files

Time:11-27

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

CodePudding user response:

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));
  • Related