Skip to content

Instantly share code, notes, and snippets.

@greg-randall
Created April 15, 2022 12:52
Show Gist options
  • Select an option

  • Save greg-randall/8cf28be7a92d8992610a377daa81f9f1 to your computer and use it in GitHub Desktop.

Select an option

Save greg-randall/8cf28be7a92d8992610a377daa81f9f1 to your computer and use it in GitHub Desktop.
Count the number of files per directory. Useful for hosting services that limit the number of files but not the size. Change $min_count to set the minimum number of files for a folder to be displayed.
<?php
$root = '.';
$min_count = 1000;
$iter = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $root, RecursiveDirectoryIterator::SKIP_DOTS ), RecursiveIteratorIterator::SELF_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD );
foreach ( $iter as $path => $dir ) {
if ( $dir->isDir() ) {
$dir_count = count_files( $path );
if ( $dir_count > $min_count ) {
$dir_size = get_dir_size( $path );
$folders[ $dir_count ] = "<tr><td>$dir_count</td><td>" . format_size( $dir_size ) . "</td><td>$path</td></tr>\n";
}
}
}
krsort( $folders );
echo "Minimum File Count: $min_count<br>";
echo '<table border="1"><tr><th>Count of Files</th><th>Size</th><th>Directory</th></tr>';
foreach ( $folders as $folder ) {
echo $folder;
}
echo "</table>";
function get_dir_size( $directory ) {
$size = 0;
foreach ( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $directory ) ) as $file ) {
$size += $file->getSize();
}
return $size;
}
function format_size( $size ) { //https://stackoverflow.com/posts/2510459/revisions
if ( $size >= 1 ) {
$si_prefix = array(
'B',
'KB',
'MB',
'GB',
'TB',
'PB',
'EB',
'ZB',
'YB'
);
$base = 1024;
$class = min( (int) log( $size, $base ), count( $si_prefix ) - 1 );
return ( sprintf( '%1.2f', $size / pow( $base, $class ) ) . $si_prefix[ $class ] );
} else {
return ( 0 );
}
}
//https://stackoverflow.com/a/41848361
function count_files( $dirname ) {
$path = realpath( $dirname );
$objects = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ), RecursiveIteratorIterator::SELF_FIRST );
$count = iterator_count( $objects );
return ( $count );
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment