I have a webcam that uploads an image every hour to a folder on a server. At the end of the day I want to delete all the images except for the image with datetime closest to 12 noon, which I keep for historical use.
This part works and finds the closest image to 12 noon and puts them in an array sorted by the difference in seconds.
What I cannot figure out is how to delete all the files except for the file with the lowest seconds, which should be the first element in the array.
If there is a better way, I am open to learning.
Thanks in advance.
This part works and finds the closest image to 12 noon and puts them in an array sorted by the difference in seconds.
PHP:
<?php
date_default_timezone_set("America/Chicago");
$today = new DateTime();
$startday = $today->setTime(0,1);
$startday = $startday->getTimestamp();
$tnoon = $today->setTime(12,0);
$tnoon = $tnoon->getTimestamp();
$diff = array();
$dir = "camgallery";
$fileSystemIterator = new FilesystemIterator($dir);
/* create array containing datediff and filename */
foreach ($fileSystemIterator as $fileInfo) {
if ($fileInfo->isFile() && $fileInfo->getCTime() >= $startday) {
$seconds = abs($tnoon - $fileInfo->getCTime());
$diff[] = ['timediff' => $seconds,
'filename' => $fileInfo->getFilename()
];
}
}
/*sort array by seconds */
array_multisort(array_column($diff, 'timediff'), SORT_ASC, $diff);
?>
What I cannot figure out is how to delete all the files except for the file with the lowest seconds, which should be the first element in the array.
PHP:
/*delete all files except for first file in array */
for ($i = 1; $i < count($diff); $i++) {
unlink($dir . "/" . [$i]['filename']);
}
If there is a better way, I am open to learning.
Thanks in advance.