I am looking to select files over a certain age from a local directory tree. The following code works but is very inefficient, and because the directory is so large, it causes timeouts.
$dir = new RecursiveDirectoryIterator('store/', FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS);
$files = new RecursiveCallbackFilterIterator($dir, function ($current, $key, $iterator) {
// Allow recursion
if ($iterator->hasChildren()) {
return TRUE;
}
// Check for target folder name
if ($current->isFile() && strpos($current->getPath(), '/target-folder/')) {
return TRUE;
}
return FALSE;
});
$expiry = new DateTime();
$expiry = date_modify($expiry,"-28 days");
foreach (new RecursiveIteratorIterator($files) as $file) {
$cTime = new DateTime();
$cTime->setTimestamp($file->getCTime());
if ($cTime < $expiry) {
echo $file->getPath() . "/" . $file->getFileName() . " file Created " . $cTime->format('Y-m-d j:i:s') . "<br/>\n";
}
}
At the moment the code is scanning every file and folder and just returning the matches, but I know that the target-folder is always 3 levels deep (store/[sub-folder]/[sub-folder]/target-folder/[recursive search from here]) so I am searching the top 2 levels for nothing. However there is not always a target folder and I also need to search recursively within the target folder as the files I need will be in it's children. Is there any way to ignore the top 2 levels within the 'store' tree?