<?PHP
  // Original PHP code by Chirp Internet: www.chirpinternet.eu
  // Please acknowledge use of this code by including this header.

  class FieldSortHeap extends SplHeap
  {
    private $sortField;

    public function __construct($sortField)
    {
      $this->sortField = $sortField;
    }

    public function compare($a, $b)
    {
      return strnatcmp($b[$this->sortField], $a[$this->sortField]);
    }
  }

  function getFilteredFileList($pattern, $orderby)
  {
    $retval = new FieldSortHeap($orderby);

    try {
      $g = new GlobIterator($pattern);
    } catch (RuntimeException $e) {
      // handle exception
    }

    foreach($g as $fileinfo) {
      $retval->insert(
        array(
          'name' => "$fileinfo",
          'type' => ($fileinfo->getType() == "dir") ? "dir" : mime_content_type($fileinfo->getRealPath()),
          'size' => $fileinfo->getSize(),
          'lastmod' => $fileinfo->getMTime()
        )
      );
    }

    return $retval;
  }
?>

<h1>Sorting the output</h1>

<table class="collapse" border="1">
<thead>
<tr>
<th></th><th>Name</th><th>Type</th><th>Size</th><th>Last Modified</th>
</tr>
</thead>
<tbody>
<?PHP
  $dirlist = getFilteredFileList('images/*.png', 'size');
  foreach($dirlist as $file) {
    echo "<tr>\n";
    echo "<td><img src=\"{$file['name']}\" width=\"64\" alt=\"\"></td>\n";
    echo "<td>{$file['name']}</td>\n";
    echo "<td>{$file['type']}</td>\n";
    echo "<td>{$file['size']}</td>\n";
    echo "<td>",date('r', $file['lastmod']),"</td>\n";
    echo "</tr>\n";
  }
?>
</tbody>
</table>