Clue Mediator

Delete files older than x days or after x amount of time in PHP

📅March 25, 2021
🗁PHP

Today we’ll show you how to delete files older than x days or after x amount of time in PHP. Sometimes we need to delete files older than `n` number of days from a specific directory.

You can also use the following article to delete all files and subfolders from the directory.

In this article, we will show you a simple way to remove files older than specified days or time from the directory using PHP.

Delete files from directory

  1. Older than x days
  2. Older than x amount of time
  3. Delete files and subfolders older than x amount of time

1. Older than x days

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);
?>

2. Older than x amount of time

Now, we will write a script to delete files that are x amount of time old.

<!--?php
$x = 21600;  // 6 hours - 6*60*60
$current_time = time();
$path = './uploads/';<p-->

$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);
    }
  }
}
?>

3. Delete files and subfolders older than x amount of time

If you want to delete files and subfolders based on the given time then you can use the following code. (Thanks, Amir for sharing your knowledge with us.)

<!--?php
// function to delete all files and subfolders from folder
function deleteAll($dir, $t, $remove = false) {
  $current_time = time();
  $structure = glob(rtrim($dir, "/").'/*');
  if (is_array($structure)) {
    foreach($structure as $file) {
      $file_creation_time = filemtime($file);
      $difference = $current_time - $file_creation_time;
      if (is_dir($file))
        deleteAll($file, $t, true);
      else if(is_file($file)) {
        if ($difference -->= $t) {
          unlink($file);
        }
      }
    }
  }
  if($remove && count(glob(rtrim($dir, "/").'/*')) == 0){
    rmdir($dir);
  }
}

$path = "uploads/";
$time = 21600; // 6 hours - 6*60*60

// call the function
deleteAll($path, $time); exit;
?>

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂