Find oldest file in a folder using PHP
file, php, sorting
Solution
// 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.
Problem
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?