Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove files/folders older than a certain time

Tags:

php

I already use a function do delete all files and folders within a certain folder.

function rrmdir($dir) {
    if (is_dir($dir)) {
        $objects = scandir($dir);
        foreach ($objects as $object) {
            if ($object != "." && $object != "..") {
                if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
            }
        }
        reset($objects);
        rmdir($dir);
    }
}

What I want to do now is: adapt that function to only delete files and folders older than 60 minutes (for instance).

There's a php function 'filetime' that I believe it gives the file/folder age, but I don't know how to delete specifically files older than "x" minutes.

like image 323
Tiago Avatar asked Sep 14 '25 01:09

Tiago


1 Answers

This construct will delete files older than 60 minutes (3600 seconds) using the filemtime() function:

if (filemtime($object) < time() - 3600) {
  // Remove empty directories...
  if (is_dir($object)) rmdir($object);
  // Or delete files...
  else unlink($object);
}

Note that for rmdir() to work, the directory must be empty.

like image 86
Michael Berkowski Avatar answered Sep 16 '25 17:09

Michael Berkowski