I am trying to create a function that removes the oldest files based on date, for a max of 30 files. I grab all the files in the dir. If there are more than 30, they get sorted by date. Then the oldest gets deleted.
public function cleanUpFolder($path){
$files = [];
try {
$dir = new DirectoryIterator($path);
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
$files[] = $fileinfo;
// in here i can call any valid method like getPathname()
}
}
$fileCount = count($files);
if($fileCount > self::MAX_BACKUPS){
// sort with the youngest file first
usort($files, function($a, $b) {
// in here, i can call functions like getMTime()
// and even getPath()
// but getPathname or getFileName return false or ""
return $a->getMTime() < $b->getMTime();
});
for($i = $fileCount - 1; $i > 30; $i--){
unlink($files[$i]->getPathname());
}
}
return true;
}
catch (Exception $e){
return false;
}
}
What is working
- Getting the files
What is not working
Sort? I cannot tell if the sort works
Calling some methods on the DirectoryIterator while looping through the
$files
array
It seems like putting the $fileInfo
into an array, most function calls no longer work..