Delete files older than 2 months old in a directory in PHP
Here, we will create a function where we will pass two parameters, first one is directory/folder path and second parameter is number of days.
This script deletes files from specified folder only, not from child folders.
<?php
function deleteOlderFiles($path,$days) {
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
$filelastmodified = filemtime($path . $file);
if((time() - $filelastmodified) > $days*24*3600)
{
if(is_file($path . $file)) {
unlink($path . $file);
}
}
}
closedir($handle);
}
}
$path = './uploads/';
$days = 2;
deleteOlderFiles($path,$days);
?>
Older than x amount of time
<?php
$x = 21600; // 6 hours - 6*60*60
$current_time = time();
$path = './uploads/';
$files = glob($path.'/*.*');
foreach($files as $file) {
$file_creation_time = filemtime($file);
$difference = $current_time - $file_creation_time;
if(is_file($file)) {
if ($difference >= $x) {
unlink($file);
}
}
}
?>