PlasmaDan
PlasmaDan

Reputation: 495

Getting RecursiveIteratorIterator to skip a specified directory

I'm using this function to get the file size & file count from a given directory:

function getDirSize($path) {
    $total_size = 0;
    $total_files = 0;

    $path = realpath($path);
    if($path !== false){
        foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object) {
            $total_size += $object->getSize();
            $total_files++;
        }
    }

    $t['size'] = $total_size;
    $t['count'] = $total_files;
    return $t;
}

I need to skip a single directory (in the root of $path). Is there a simple way to do this? I looked at other answers referring to FilterIterator, but I'm not very familiar with it.

Upvotes: 2

Views: 361

Answers (1)

mhall
mhall

Reputation: 3701

If you don't want to involve a FilterIterator you can add a simple path match:

function getDirSize($path, $ignorePath) {
    $total_size = 0;
    $total_files = 0;

    $path = realpath($path);
    $ignorePath = realpath($path . DIRECTORY_SEPARATOR . $ignorePath);

    if($path !== false){
        foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object) {
            if (strpos($object->getPath(), $ignorePath) !== 0) {
                $total_size += $object->getSize();
                $total_files++;
            }
        }
    }

    $t['size'] = $total_size;
    $t['count'] = $total_files;
    return $t;
}

// Get total file size and count of current directory,
// excluding the 'ignoreme' subdir
print_r(getDirSize(__DIR__ , 'ignoreme'));

Upvotes: 1

Related Questions