2015-02-12 48 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'));