Search code examples
phpdatedatetimefilemtime

find files modified between two dates using php


I'm getting thoroughly confused about the various date functions and formats in php so I would like to ask for help if possible.
I'm trying to find files that were modified between two dates but the syntax is confusing me. For instance, if I tried to find files altered between 6 months and 1 year ago, I have tried:

$yearago = new DateTime("now");
date_sub($yearago, date_interval_create_from_date_string("1 year"));

$sixmonthsago = new DateTime("now");
date_sub($sixmonthsago, date_interval_create_from_date_string("6 months"));

$dir    = '/datacore/';
$files1 = scandir($dir);

foreach($files1 as $key => $value)
{

    $datemod = filemtime($value);

    if ($datemod>$yearago && $datemod<$sixmonthsago) // eg between 6 and 12 months ago
    {
    // Do stuff
    }

}

I know this is inefficient; finding an array of filenames in the directory and then looping through this array on filemtime but this is something to work on in the future, but its the mix of date and DateTime thats got me confused.


Solution

  • You don't assign your date_sub values back to your variables, so the "subtracted" values are simply lost. You should have had:

    $yearago = date_sub($yearago,  ...);
    

    Plus, you can simply tell DateTime to generate the proper dates to start with:

    $yearago = new DateTime("1 year ago");
    $sixmonths = new DateTime('6 months ago');
    

    Note that $yearago and $sixmonths are DateTime objects, while filemtime() returns a standard Unix timestamp, and you cannot compare them directly.

    So you might as well just have

    $yearago = strtotime('1 year ago');
    $sixmonths = strtotime('6 months ago');
    

    which gives you timestamps to start with, no further conversion needed