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?
// 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.
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.
More memory efficient way of doing this, here I never store more than one file name in memory at a time :
<?php
$directory= "C:\\";
$smallest_time=INF;
$oldest_file='';
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
$time=filemtime($directory.'/'.$file);
if (is_file($directory.'/'.$file)) {
if ($time < $smallest_time) {
$oldest_file = $file;
$smallest_time = $time;
}
}
}
closedir($handle);
}
echo $oldest_file;
ran on a folder with 4000 files and used 85% less ram than storing the file names.
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;
}
精彩评论