Search code examples
phpopendir

Get specific number of files from a directory ordered by time modified


I'm trying to write a function that returns and array of the files names ordered by time modified. Although I want to get only a specific number of files, and not the whole files in the directory. In conclusion, I'd like to get an array that contains the newest X files from a directory.

This is my code:

    public static function GetPicsDir()
    {
        $results = array();
        $handler = opendir("pics");
        while ($file = readdir($handler)) {
          if ($file != "." && $file != "..") {
            $results[] = $file;
          }
        }
        closedir($handler);
        return $results;
    }

I don't know how to limit it and order by time modified. I'd be glad to get any help.

Thank you


Solution

  • You can use glob

    $date = strtotime('2013-01-10 10:00:00');//The date from you want to get the files
    $matches = glob('dir/*.*');
    $result=array();
    if (is_array($matches)) {
      $a=0;
      foreach ($matches as $filename) {
        if (filemtime($filename) >= $date) {//only output file >= your $date
          $result[$a]['FileName'] = $filename;
          $result[$a]['DateCreated'] = gmdate("Y-m-d H:i:s", filemtime($filename));
        }
          $a++;
      }
    }
    
    if(count($result)>=2){//order array if it has at least 1 match
       foreach ($result as $key => $row) {
          $new_array[$key] = $row['DateCreated'];
        }
     array_multisort($new_array,SORT_DESC,$result);//Show most recent first 
    }
    

    using array_multisort to sort by dates SORT_DESC

    echo '<pre>';
    print_r($result);
    echo '<pre>';
    

    Output:

    Array
    (
      [0] => Array
          (
              [FileName] => test.php
              [DateCreated] => 2013-10-20 05:43:06
          )
    
      [1] => Array
          (
              [FileName] => test.sql
              [DateCreated] => 2013-09-20 23:38:05
          )
    
      [2] => Array
          (
              [FileName] => general.php
              [DateCreated] => 2013-09-02 00:58:33
          )
    
    )