/*
a php solution
$dirin the directory to check
$numToKeep - keep the latest X number of files
*/
function cleanUpFiles($dirin,$numToKeep) {
// 1- get a list of file for the directory
$f1 = new FilesystemIterator($dirin, FilesystemIterator::SKIP_DOTS);
gjLog($dirin. " number of files : ". iterator_count($f1),'clean.log');
$gjcount=0; // start at
if(iterator_count($f1) < $numToKeep){
gjLog('Number of Files less than number to keep: '. $numToKeep. ' Nothing to unlink'.PHP_EOL,'clean.log');
return;
}
// 2- create an array of files to sort by Modified Time in step 3
$thefiles = array();
foreach($f1 as $fileinfo) {
$akey = $f1->getFileName();
if((strtolower($akey)) != 'index.html') {
$thefiles[$akey] = $f1->getMTime();
}
}
// 3- sort the files by date - descending newest first
arsort($thefiles);
// 4- start at 0, after 10 files delete the rest
foreach ($thefiles as $key => $value) {
if($numToKeep < $gjcount){
$killme = $dirin. DIRECTORY_SEPARATOR. $key;
gjLog('unlinking these files: '. $killme,'clean.log');
if(!unlink($killme)) {
$err ='unable to unlink '. $killme.PHP_EOL;
gjLog($err,'clean.log');
// when in cron job, I check for Fatal in the mail
echo $err. ' Fatal Error in'. __FILE__. PHP_EOL;
}
}
$gjcount++;
}
}
// cleanup application logs
$dirin = '/var/www/html/application/logs';
$numToKeep=30; // total number to keep
cleanUpFiles($dirin,$numToKeep);
</pre>
Gary Johnson
28.01.2020, 00:58
Ссылка