Skip to main content

Delete files in a folder older than a set date

<?php

// Set expiry time
$expire_timestamp = strtotime('now - 2 days');

// Set backup folder to delete files from
$backup_dir = '/var/www/html/live/sites/default/files/analytics';
// Open the folder
if ($dh = opendir($backup_dir)) {
//    Loop through all files in the folder
    while ($file = readdir($dh)) {
// using regular expressions, to match files named as visit_log_2012-05-25.csv
        if (preg_match('#^visit_log_(\d{4}-\d{2}-\d{2})#', $file, $matches)) {
//    convert the match to timestamp          
          $file_timestamp = strtotime($matches[1]);
//    If the match is less than expiry date set, delete it.          
          if ($file_timestamp < $expire_timestamp) {
            $del_cmd = sprintf('rm %s/%s', $backup_dir, $file);
//            print $del_cmd . "\n<br/>";
            exec($del_cmd);
          }        
        }
        if (preg_match('#^events_log_(\d{4}-\d{2}-\d{2})#', $file, $matches)) {
          $file_timestamp = strtotime($matches[1]);
        
          if ($file_timestamp < $expire_timestamp) {
            $del_cmd = sprintf('rm %s/%s', $backup_dir, $file);
//            print $del_cmd . "\n<br/>";
            exec($del_cmd);
          }        
        }        
    }
    
}