2015-02-12 93 views
2

我使用这个功能,从给定的目录获取文件大小&文件数:获取RecursiveIteratorIterator跳过指定的目录

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

我需要跳过一个目录($的根路径)。有没有简单的方法来做到这一点?我查看了其他有关FilterIterator的答案,但我并不十分熟悉它。

回答

1

如果你不想涉及FilterIterator你可以添加一个简单的路径匹配:

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