1

I have a lot of files in a directory. And I want to delete the file(s) which is/are older than 10 hours (created at least 10 hours ago). How do I do that in PHP?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
mukto90
  • 367
  • 2
  • 4
  • 15

2 Answers2

1

Here is code for you

<?php
    $dir = '/path/to/my/dir';
    $files = scandir($dir);
    $cnt = count($files);
    $deadline = strtotime('now')-36000;
    for($i = 0; $i < $cnt; ++$i)
    {
        $files[$i] = $dir.'/'.$files[$i];
        if(!is_file($files[$i]) || $files[$i] == '.' || 
            $files[$i] == '..' || filemtime($files[$i]) <= $deadline)
            unset($files[$i]);
        else
            unlink($files[$i]);
    }
fiction
  • 566
  • 1
  • 6
  • 21
0

PHP has function filemtime() which return the last modified date.

if ((time() - filemtime($filename)) > 60 * 60 * 10) {
    unlink($filename);
}
pavel
  • 26,538
  • 10
  • 45
  • 61