PHP: List files in directory over certain size – sorted

1 min read

Avoids the filesize(): stat failed error and can be run from another directory. Sorts files by size.

files-fouond

This does NOT include an extension filter but the code is there to grab the extension.

 

$threshold = 75000; // minimum file size to display in bytes
$num = 50; // number of files you want to list in the echo
$path = "/path/to/file/"; // directory path off of root

$dir = "..".$path;

$i=0;
if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle)))
    {   
        if (($file != ".") 
         && ($file != ".."))
        {
               $filename = $_SERVER["DOCUMENT_ROOT"] . $path.$file; // avoids "filesize(): stat failed" error
               $info = new SplFileInfo($filename);
               $ext = $info->getExtension(); // use this to grab extension if you want to filter by file type
               $size = filesize($filename);
		
	               if ($size > $threshold) {
	               $kb = formatBytes($size, 1);
	               $big[$i] = array($size,$file,$kb);
	 	       $i++;
	 	       }
        }
    }

    closedir($handle);
}

rsort($big); // sort by size big to small

$j=0;
while($big[$j] and $j<$num){
$thelist .= '

‘; $j++; } function formatBytes($size, $precision = 2) { $base = log($size, 1024); $suffixes = array(”, ‘Kb’, ‘Mb’, ‘Gb’, ‘Tb’); return round(pow(1024, $base – floor($base)), $precision) .’ ‘. $suffixes[floor($base)]; }

Output

Total files found over <!--?php echo $threshold ?--> bytes : <!--?php echo $i; ?-->

List of biggest files: