0

Possible Duplicate:
How to delete files from directory based on creation date in php?

How would i delete all the images in a folder that are 24 hours old or older in php?

Community
  • 1
  • 1
Keverw
  • 3,736
  • 7
  • 31
  • 54

5 Answers5

4
$imagePattern = "/\.(jpg|jpeg|png|gif|bmp|tiff)$/";
$directory = ".";

if (($handle = opendir($directory)) != false) {
    while (($file = readdir($handle)) != false) {
        $filename = "$directory/$file";
        if (strtotime("-24 hours") <= filemtime($filename) && preg_match($imagePattern, $filename)) {
            unlink($filename);
        }
    }

    closedir($handle);
}
Ewan Heming
  • 4,628
  • 2
  • 21
  • 20
3

If you're on *nix, punt it off to the shell and find:

shell_exec('find /path/to/your/directory -mtime +0 -exec rm -f {} \;');
Rob Agar
  • 12,337
  • 5
  • 48
  • 63
1

combination of:

to check time http://us2.php.net/manual/en/function.filemtime.php

to delete http://us2.php.net/manual/en/function.unlink.php

bensiu
  • 24,660
  • 56
  • 77
  • 117
1

An alternate solution would be to use a naming convention that includes a unix timestamp if you have control over that.

Syntax Error
  • 4,475
  • 2
  • 22
  • 33
0
shell_exec('find /path/to/files* -mtime +1 -exec rm {} \;');
Thor
  • 45,082
  • 11
  • 119
  • 130
FatherStorm
  • 7,133
  • 1
  • 21
  • 27
  • 1
    Won't work on servers without `find` in the search path, including Windows machines and locked down Linux machines. – Charles Mar 13 '11 at 04:37