Get most recent files recursively with PHP

前端 未结 4 1673
独厮守ぢ
独厮守ぢ 2021-01-24 04:54

I am looking for code which lists the five most recent files in a directory recursively.

This is non-recursive code, and would be perfect for me if it was recursive:

相关标签:
4条回答
  • 2021-01-24 05:30

    This is pretty quick and dirty, and untested, but might get you started:

    function top5mods($dir)
    {
      $mods = array();
      foreach (glob($dir . '/*') as $f) {
        $mods[] = filemtime($f);
      }
      sort($mods);
      $mods = array_reverse($mods);
      return array_slice($mods, 0, 5);
    }
    
    0 讨论(0)
  • 2021-01-24 05:31

    Edit : Sorry I didn't see the part "recursively".

    To get RECENTS files first (html for example), please sort like this with anonymous function :

    $myarray = glob("*.*.html");
    usort($myarray, function($a,$b){
      return filemtime($b) - filemtime($a);
    });
    

    And to get it recursively you can :

    function glob_recursive($pattern, $flags = 0) {
        $files = glob($pattern, $flags);
        foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
            $files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
        }
        return $files;
    }
    

    So, replace then the glob function by :

    $myarray = glob_recursive("*.*.html");
    usort($myarray, function($a,$b){
      return filemtime($b) - filemtime($a);
    });
    
    0 讨论(0)
  • 2021-01-24 05:32

    This was my first version (tested, working):

    function latest($searchDir, array $files = array()) {
        $search = opendir($searchDir);
    
        $dirs = array();
        while($item = readdir($search)) {
            if ($item == '.' || $item == '..') { continue; }
            if (is_dir($searchDir.'/'.$item)) {
                $dirs[] = $searchDir.'/'.$item;
            }
            if (is_file($searchDir.'/'.$item)) {
                $ftime = filemtime($searchDir.'/'.$item);
                $files[$ftime] = $searchDir.'/'.$item;
            }
        }
        closedir($search);
        if (count($dirs) > 0) {
            foreach ($dirs as $dir) {
                $files += latest($dir,$files);
            }
        }
        krsort($files);
        $files = array_slice($files, 0, 5, true);
        return $files;
    }
    

    But I like byte's usage of glob(), so here is a slightly modified version of his to return the same format:

    function top5modsEx($dir) {
        $mods = array();
        foreach (glob($dir . '/*') as $f) {
            $mods[filemtime($f)] = $f;
        }
        krsort($mods);
        return array_slice($mods, 0, 5, true);
    }
    

    This returns the time (UNIX Timestamp format) that the file was modified as the key of the element in the array.

    0 讨论(0)
  • 2021-01-24 05:32

    Check out this solution in the PHP manual.

    0 讨论(0)
提交回复
热议问题