Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find oldest file in a folder using PHP

Tags:

file

php

sorting

I need a PHP script that will find the date of the oldest file in a folder. Right now, I am iterating 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 folder in Windows Explorer, it will auto sort by date modified and I see the oldest file a lot faster. Is there any way I can take advantage of Explorer's default sort from a PHP script?

like image 348
BLAKE Avatar asked Nov 23 '09 18:11

BLAKE


2 Answers

// 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.

like image 178
Anthony Forloney Avatar answered Oct 13 '22 01:10

Anthony Forloney


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.

like image 42
Frank Farmer Avatar answered Oct 13 '22 01:10

Frank Farmer