Radek
Radek

Reputation: 11101

Get the newest file from directory structure year/month/date/time

I store backups of databases in a directory structure

year/month/day/time/backup_name

an example would be

basics_mini/2012/11/05/012232/RATIONAL.0.db2inst1.NODE0000.20110505004037.001 basics_mini/2012/11/06/012251/RATIONAL.0.db2inst1.NODE0000.20110505003930.001

note that timestamp from the backup file cannot be used. Before the automation testing starts the server time is set to 5.5.2011

So the question is how I can get the latest file if I pass the "base directory" (basics_mini) to some function that I am going to code. My thoughts are that I list the base directory and sort by time to get the year. Then I do the same for month, day and time.

I wonder if there is any "easier" solution to that in php.

Upvotes: 0

Views: 297

Answers (2)

glasz
glasz

Reputation: 2565

I don't know of any amazingly simple one-liner but it looks like this might be helpful:

$files = array();
$flags = FilesystemIterator::CURRENT_AS_SELF;
$dir = new RecursiveDirectoryIterator('/path/to/basics_mini', $flags);
foreach ($dir as $path) {
    if ($path->isFile()) {
        $files[$path->getPath()] = $path->getFilename();
    }
}

ksort($files);

You might want to use a RecursiveDirectoryIterator because your directory structure is a little more complex.
The FilesystemIterator constants can also be helpful.

Upvotes: 1

dev-null-dweller
dev-null-dweller

Reputation: 29462

Well, you can fetch whole directory tree at once and get last elem from it:

$baseFolder = './backup_mini' ;

$arr = glob("{$baseFolder}/*/*/*/*", GLOB_ONLYDIR);
$lastDir = array_pop($arr);

Upvotes: 1

Related Questions