Thursday, May 1, 2014

PHP listing files inside directory i.e. sorted by modifcation date.

Normally for listing files from directory normally we use the following methods : readir()/scandir() etc.

But if we needed file list sorted by modification date.Then one of the possible simple solution(using DirectoryIterator) is


<?php
$fileListing = array();
$directory=".";
$directoryToProcess = new DirectoryIterator($directory);
foreach ($directoryToProcess as $listedFileInfo) {     
if ($listedFileInfo->getFileName() != "." && $listedFileInfo->getFileName() != "..")
        {
$fileListing[$listedFileInfo->getFileName()]=$listedFileInfo->getMTime();
}
}
arsort($fileListing);
foreach($fileListing as $fileName=>$fileNameTimeStamp)
{
      #Perform action here
echo $fileName."\n";
}
?>


Reference
----------------
Different answers in Stackoverflow

No comments: