skip to Main Content

I want to be able to delete all files in a directory that older than seven days old using only PHP. How can I do this? The server is using Debian Linux.

2

Answers


  1. The 604800 is how many seconds are in a week.

    $path="whateverdir/";
    (time()-filectime($path.$file)) > 604800;
    unlink($path.$file);
    

    If you have more than one directory, you would have to do this for each directory.

    Login or Signup to reply.
  2. A simple PHP function to delete files older than a given age. Very handy to rotate backup or log files, for example…

    <?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 = "/my/backups";
    $to = "[email protected]";
    
    // Delete backups older than 7 days
    $deleted = delete_older_than($dir, 3600*24*7);
    
    $txt = "Deleted " . count($deleted) . " old backup(s):n" .
    implode("n", $deleted);
    
    mail($to, "Backups cleanup", $txt);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search