tags:

views:

51

answers:

3

I am looking for a code, which I can use for list 5 most recent files recursively in a directory.

Here is a non-recursive code, this one will be perfect for me if it was recursive:

    <?php

$show = 0; // Leave as 0 for all
$dir = 'sat/'; // Leave as blank for current

if($dir) chdir($dir);
$files = glob( '*.{html,php,php4,txt}', GLOB_BRACE );
usort( $files, 'filemtime_compare' );

function filemtime_compare( $a, $b )
{
    return filemtime( $b ) - filemtime( $a );
}
$i = 0;
foreach ( $files as $file )
{
    ++$i;
    if ( $i == $show ) break;
    echo $file . ' - ' . date( 'D, d M y H:i:s', filemtime($file) ) . '<br />' . "\n";  /* This is the output line */
}
?>

It is possible to modify it to scan dirs recursively?

A: 

Check out this solution in the PHP manual.

dnagirl
+1  A: 

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);
}
byte
A: 

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.

Dereleased
Working like a charm! Is there any way to exclude files from the search?
Peter
|| $item == 'exclude this' --- this is the solution.Thank you very much again!
Peter