Search form

PHP: List Last Updated Files

An old PHP script to list the most recently updated files within a web site using their 'last modified' time stamps.

<?php
  
$rootdir = $_SERVER['DOCUMENT_ROOT'];

if ($dir = opendir($rootdir . '/my/web/site')) {
    $filearray = array();
    $i = 0;
    $exclusions = array('.', '..', 'inc', 'css', 'images'); 

    while (false !== $file = readdir($dir)) {
        if (is_dir($rootdir . '/my/web/site/' . $file) && !in_array($file, $exclusions)) {
             $subdir = opendir($rootdir . '/my/web/site/' . $file);
             while (false !== $newfile = readdir($subdir)) {
                  if (strpos($newfile,'.php',1) && !strpos($newfile,'.php.swp',1)) {
                      $filearray[$i] = array();
                      $filearray[$i][] = $file.'/'.$newfile;
                      $i++;
                  }
             }
         } else {
	     if (strpos($file,'.php',1) && !strpos($file,'.php.swp',1)) {
                 $filearray[$i] = array();
                 $filearray[$i][] = $file;
                 $i++;
             }
         }
    }

    // Append the modified dates
    for ($j = 0; $j < count($filearray); $j++) {
        $lastmodified = filemtime($rootdir . '/my/web/site/' . $filearray[$j][0]);
        $filearray[$j][] = date('m/j/y g:i a', $lastmodified);
    }
    
    // Sort the array by the modified dates
    function comparedates($page1, $page2) {
        if (strtotime($page1[1]) == strtotime($page2[1])) {
	    return 0;
        } else if (strtotime($page1[1]) < strtotime($page2[1])) {
	    return 1;
        } else {
	    return -1;
        }
    }

    usort($filearray, 'comparedates');

    // Trim array to the four most recently updated pages
    for ($m = count($filearray) - 1; $m > 3; $m--){
        array_pop($filearray);
    }

    // Output the four sorted pages and dates
    for ($l = 0; $l < count($filearray); $l++) {
        echo '<li><a href="' . $rootdir . '/' . $filearray[$l][0].'">'.$filearray[$l][0].
             '<'/a> <span class="lastdate">('.$filearray[$l][1].')</span></li>';
        
    }

}

?>

Categories: