tags:

views:

202

answers:

3

Hey, I need a PHP script that will find the date of the oldest file in a folder. Right now, I am iterateing over every file and comparing it's Date Modified to the previous file and keeping the oldest date stored.

Is there a less disk/memory intensive way to do this? There are about 300k files in the folder. If I open the wolder in Windows Explorer, it will auto sort by date modified and I see the oldest file alot faster. Is there any way I can take advantage of Explorer's default sort from a php script?

+4  A: 
// Grab all files from the desired folder
$files = glob( './test/*.*' );

// Sort files by modified time, latest to earliest
// Use SORT_ASC in place of SORT_DESC for earliest to latest
array_multisort(
array_map( 'filemtime', $files ),
SORT_NUMERIC,
SORT_ASC,
$files
);

echo $files[0] // the latest modified file should be the first.

Taken from this website

Good luck

EDIT: To exclude files in the directory to reduce unnecessary searches:

$files = glob( './test/*.*' );
$exclude_files = array('.', '..');
if (!in_array($files, $exclude_files)) {
// Sort files by modified time, latest to earliest
// Use SORT_ASC in place of SORT_DESC for earliest to latest
array_multisort(
array_map( 'filemtime', $files ),
SORT_NUMERIC,
SORT_ASC,
$files
);
}

echo $files[0];

This is helpful if you know what to look for and what you can exclude.

Anthony Forloney
I like your answer, but with that many files, PHP runs out of memory before finishing and the script dies.
BLAKE
can you filter out certain files to not check, maybe folders, text files, scripts? $exclude_files = array('.', '..')
Anthony Forloney
No, all the files are named %timestamp-guid%.tmp. I can't exclude any files other than '.' and '..'.
BLAKE
A: 

There are some obvious disadvantages to this approach -- spawning an additional process, OS-dependency, etc., but for 300k files, this may very well be faster than trying to iterate in PHP:

exec('dir /TW /O-D /B', $output);
var_dump($output[0]);

FWIW, you should really try to avoid having 300,000 files in a single dir. That doesn't really perform well on most file systems.

Frank Farmer
I tried to do this, but iis just spawns a cmd.exe process and never ends. Even if the command I pass to it is just 'exit', The cmd.exe will never end.
BLAKE
A: 

10 months on you're probably not still looking for a solution here, but just in case:

function findOldestFile($directory) {
    if ($handle = opendir($directory)) {
        while (false !== ($file = readdir($handle))) {
            $files[] = $file;
        }

        print_r("\n");
        print_r($files);
        print_r("\n");


        foreach ($files as $file) {
            if (is_file($directory.'/'.$file)) {
                $file_date[$file] = filemtime($directory.'/'.$file);
            }
        }
    }

    closedir($handle);
    asort($file_date, SORT_NUMERIC);
    reset($file_date);
    $oldest = key($file_date);
    return $oldest;
}
n1c