Share the post "How To Delete Files Older Than N Time In PHP"
Here is a custom function I made that will delete all files in a folder older than N time.
Time here can be minutes, seconds or hours by using the strtotime() function. So for example, if you want to delete old files less than 4 hours, you can call strtotime(‘-4 hours’).
|
1 2 3 4 5 6 7 8 9 10 11 |
function deleteFilesOlderThan($path, $extension, $timeLessThan) { foreach (glob($path . '*') as $file) { if (endsWith($file, $extension) && filemtime($file) <= $timeLessThan) unlink($file); } } function endsWith($haystack, $needle) { // search forward starting from end minus needle length characters return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== FALSE); } |