-1

I am making a Cron that will delete a folder older than 15days. I already made a function to delete the folder and it's content, what I don't have is to loop inside a folder then check each folder's age then if that is 15days old or above I will executue my delete function.

I want to loop inside public/uploads

in my uploads directory I store folders with content ex.

public/
  uploads/
      Test/
      Test2/

I want to check how old those folder then delete it by calling

function Delete($path)
{
 if (is_dir($path) === true)
 {
    $files = array_diff(scandir($path), array('.', '..'));

    foreach ($files as $file)
    {
        Delete(realpath($path) . '/' . $file);
    }

    return rmdir($path);
 }

 else if (is_file($path) === true)
 {
    return unlink($path);
 }

 return false;
}

How do I do that? Thanks

jackhammer013
  • 2,295
  • 11
  • 45
  • 95

1 Answers1

0

The function you are looking for is filemtime(). This lets you determine the last modified date of a file (or directory). That in combination with the various directory functions will allow you to loop through them and check their dates.

This is something mocked up off the top of my head to give you a rough idea of how you may go about this:

$dir = '/path/to/my/folders';
$folders = scandir($dir);
foreach ($folders as $folder) {
    $lastModified = filemtime($folder);
    // Do a date comparison here and call your delete if necessary
}
Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
  • Thanks this is what I exactly need :) How the I convert $lastModified to a time format and compare it if it is greater than 15days? – jackhammer013 Jul 28 '15 at 13:47
  • We can't do everything for you here -- try doing some research and come back if you get stuck. *Hint: Search stack overflow for "php compare dates"* – Jeremy Harris Jul 28 '15 at 13:50
  • when I tried to echo date("Y-m-d H:i:s", $lastModified); it gives me 2015-07-28 14:02:40 2015-07-28 15:02:01 1970-01-01 01:00:00 why is it giving me 3 dates? where I only have 1 folder inside public/uploads/ – jackhammer013 Jul 28 '15 at 13:56
  • ...it is inside of a foreach loop. Try dumping out `$folders` and see what it is returning. Might be including the `..` and `.` directories. – Jeremy Harris Jul 28 '15 at 13:57
  • There is indeed a file inside a diretory, what if I only want to get the last datemodified of the folder the I am looping into without touching the files inside it? – jackhammer013 Jul 28 '15 at 13:59
  • $folders has 3 items? I only have 1 folder in that direcotry – jackhammer013 Jul 28 '15 at 13:59
  • Pass just the path of that folder then – Jeremy Harris Jul 28 '15 at 14:00
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/84474/discussion-between-joene-floresca-and-cillosis). – jackhammer013 Jul 28 '15 at 14:03