Jump to content

Search for newest directory


void_set

Recommended Posts

Hello how can i modify this script to search in all subdirectories to get only one new directory? THX!

 

This little script only search in current $path for newest directory but i also need to search in all subdirectories

<?php
function getNewestDir($path) {
$working_dir = getcwd();
chdir($path); ## chdir to requested dir
$ret_val = false;
if ($p = opendir($path) ) {
while (false !== ($file = readdir($p))) {
if ($file{0} != '.' && is_dir($file)) {
$list[] = date('YmdHis', filemtime($path.'/'.$file)).$path.'/'.$file;
}
}
rsort($list);
$ret_val = $list[0];
}
chdir($working_dir); ## chdir back to script's dir
return $ret_val;
} 

?>
Link to comment
Share on other sites

Using a similar function but making it recursive to search the directory tree.

$dt = 0;
$latestfile = '';
$latestdir = '';
$startDir = 'c:/inetpub/wwwroot';   // set start of search

newestDir($startDir, $dt, $latestfile, $latestdir);  // call search function

echo "$latestdir/$latestfile : " . date('Y-m-d H:i:s', $dt);  // output lastest dir/file

function newestDir($dir, &$dt, &$latestfile, &$latestdir)
{
    if ($p = opendir($dir) ) {
        while (false !== ($file = readdir($p))) {
            if ($file=='.' || $file=='..') continue;
            if (!is_dir("$dir/$file")) {
                if (($ft = filemtime("$dir/$file")) > $dt) {
                    $dt = $ft;
                    $latestdir = $dir;
                    $latestfile = $file;
                }
            }
            else {
                newestDir("$dir/$file", $dt, $latestfile, $latestdir);
            }
        }
    }
    closedir($p);
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.