Listing Directory Content Sorted By Size with PHP

By | May 27, 2008

Let’s a take a common situation – you have a directory with a big number of files and you need to sort these files by size. Here is the code that will help you to do this in PHP. Quite short and fast.

<?php
// Path to the directory with big number of files
$dir = “../files/”;

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
// Opening the directory
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
// Checking for file existence
if ($file!=”.” && $file!=”..” && file_exists($dir.$file))
// Creating an array with file names as keys and sizes as values
$sizes[$file]=filesize($dir.$file);
}
closedir($dh);
}
// Sorting the array
arsort($sizes);
// Eching these values
foreach ($sizes as $chinese=>$people)
{
echo $people.” “.$chinese.”<br>”;
}
}
?>