Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Delete all of todays files in folder except for file dated closest to 12 noon

Status
Not open for further replies.

waubain

Technical User
Dec 13, 2011
200
US
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.

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.
 
This works, but I am not sure it is the best method.

PHP:
/* delete all files except file with index 0 */
    for ($i = 1; $i < count($diff); $i++) {
        unlink($dir . "/" . $diff[$i]['filename']);
        }
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top