Skip to content

Instantly share code, notes, and snippets.

@mauron85
Last active October 21, 2019 13:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mauron85/3790e63df4157a944223238097cb579e to your computer and use it in GitHub Desktop.
Save mauron85/3790e63df4157a944223238097cb579e to your computer and use it in GitHub Desktop.
Clear camera images older then x seconds
<?php
echo "maintenance...";
define("ONE_DAY_IN_SECONDS", 86400);
function delete_files_older_than($dir, $fileDateMask, $seconds, $now = NULL) {
if (is_dir($dir) === false) {
echo "Dir $dir doesn't exists\n";
return;
}
if (is_null($now)) {
$now = time();
}
echo "Processing dir: $dir\n";
$dirIterator = new FilesystemIterator($dir);
foreach ($dirIterator as $fileInfo) {
if ($fileInfo->isDir()) {
delete_files_older_than($fileInfo->getPathname(), $fileDateMask, $seconds, $now);
$subdirIterator = new FilesystemIterator($fileInfo->getRealPath());
if (!$subdirIterator->valid()) {
echo "Deleting empty dir:" . $fileInfo->getRealPath() . "\n";
rmdir($fileInfo->getRealPath());
}
} else if ($fileInfo->isFile()) {
$fileName = $fileInfo->getFilename();
if (preg_match($fileDateMask, $fileName, $matches)) {
$fileDate = date_create_from_format('YmdHis', $matches[1]);
if ($fileDate === false) {
continue;
}
$fileTimestamp = date_timestamp_get($fileDate);
$fileAge = $now - $fileTimestamp;
if ($fileAge >= $seconds) {
echo "Will delete file: " . $fileInfo->getFilename() . " age: " . $fileAge . "s\n";
unlink($fileInfo->getRealPath());
} else {
echo "Will keep file: " . $fileInfo->getFilename() . " age: " . $fileAge . "s\n";
}
}
}
}
}
//clearstatcache();
//header("Content-Type: text/plain");
$now = time();
$safeMode = ini_get('safe_mode');
echo "Safe mode: $safeMode\n";
echo "Now timestamp: $now\n";
echo "Max file age: " . ONE_DAY_IN_SECONDS . "s\n";
$dirName = realpath(dirname(__DIR__) . DIRECTORY_SEPARATOR . 'cam');
delete_files_older_than($dirName, '/camera[0-9]*_([0-9]+)\.jpg/', ONE_DAY_IN_SECONDS, $now);
delete_files_older_than($dirName, '/timelapse.webm/', ONE_DAY_IN_SECONDS, $now);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment