Created
March 7, 2024 17:30
-
-
Save dubrod/418349c05060193e691d404359937d59 to your computer and use it in GitHub Desktop.
MODX Delete Old Files on Form Submit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* A simple function that uses mtime to delete files older than a given age (in seconds) | |
* Very handy to rotate backup or log files, for example... | |
* | |
* $dir String whhere the files are | |
* $max_age Int in seconds | |
* return String[] the list of deleted files | |
*/ | |
function delete_older_than($dir, $max_age) { | |
$list = array(); | |
$limit = time() - $max_age; | |
$dir = realpath($dir); | |
if (!is_dir($dir)) { | |
return; | |
} | |
$dh = opendir($dir); | |
if ($dh === false) { | |
return; | |
} | |
while (($file = readdir($dh)) !== false) { | |
$file = $dir . '/' . $file; | |
if (!is_file($file)) { | |
continue; | |
} | |
if (filemtime($file) < $limit) { | |
$list[] = $file; | |
unlink($file); | |
} | |
} | |
closedir($dh); | |
return $list; | |
} | |
// An example of how to use: | |
$dir = "/paas/c1308/www/assets/photos"; | |
// Delete backups older than 7 days | |
$deleted = delete_older_than($dir, 3600*24*7); | |
//if(is_array($deleted)){ | |
//$txt = "Deleted " . count($deleted) . " old backup(s):\n" .implode("\n", $deleted); | |
//$modx->log(modX::LOG_LEVEL_ERROR,'AlphaToro: ' . $txt); | |
//} | |
return true; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment