Reputation: 2357
I have a directory named 'backup'
its contains following files (with some specific details)
No---File Name----------------------------------------------------------------Date--------------------Time-----------Size
1. blog-backup_on_11-April-2012_at_08-22-18AM.zip 11-April-2012 08:22:18AM 5.28MB
2. blog-backup_on_11-April-2012_at_08-25-24AM.zip 11-April-2012 08:25:25AM 5.28MB
3. blog-backup_on_11-April-2012_at_08-25-46AM.zip 11-April-2012 08:25:47AM 5.28MB
4. blog-backup_on_11-April-2012_at_08-26-07AM.zip 11-April-2012 08:26:08AM 5.28MB
5. blog-backup_on_11-April-2012_at_08-27-52AM.zip 11-April-2012 08:27:53AM 5.28MB
I want to get oldest file from 'backup' directory
Like 'blog-backup_on_11-April-2012_at_08-22-18AM.zip' its the oldest file in directory.
I tried this link but unable to handle logic.
Please give some suggestion, how to get this file?
Upvotes: 1
Views: 1918
Reputation: 3144
Unless one can make a clear one-liner of some kind, which I do not yet see here. I prefer readable and comprehensible algorithms that do not rely on you remembering what the various sort function do.
$latest_file_time = 0;
foreach(glob("backup/*") as $this_filename){
$file_changed_time = filemtime($this_filename);
if($file_changed_time > $latest_file_time){
$latest_file = $this_filename;
$latest_file_time = $file_changed_time;
}
}
echo "latest file time = $latest_file_time latest file name = $latest_file";
Upvotes: 0
Reputation: 17894
$dir = 'path/to/backup/';
foreach (glob($dir.'*.zip') as $filename) {
$time = filemtime($filename);
$files[$time] = $filename;
}
krsort($files);
echo reset($files);
Upvotes: 2
Reputation: 131
I'm not sure why the previous answers are mentioning krsort();
as it actually makes the first element the newest file. Using
ksort($file_arr);
echo reset($file_arr);
will echo the oldest file. The beginning code as already mentioned doesn't need to be changed.
Upvotes: 0
Reputation: 1731
try this:
$dir_path = 'c:/my_dir';
if($handle = opendir($dir_path))
{
while(false !== ($entry = readdir($handle)))
{
$created = filemtime($dir_path . $entry);
$myfiles[$created] = $entry;
}
krsort($myfiles); //first element is oldest file
print_r($myfiles);
}
Upvotes: 1