Skip to content
Advertisement

How to use PHP glob() with minimum file date (filemtime)?

I want to get a range of files with PHP glob function, but no older than a month (or other specified date range).

My current code:

$datetime_min = new DateTime('today - 4 weeks');

$product_files = array();
foreach(glob($image_folder.$category_folder.'*'.$img_extension) as $key => $product) if (filemtime($product)>$datetime_min) { $product_files[] = $product; }

This returns an error:

Notice: Object of class DateTime could not be converted to int

I think it still gives me a result with all files in that folder. So my approach could be completely wrong.

How can I make this code work, so I only have an array with files no older than the specified date?

Advertisement

Answer

filemtime() returns a Unix timestamp which is an integer. DateTime objects are comparable but only to each other. You’ll need either need to convert them into Unix timestamps or convert the result of filemtime() into a DateTime object.

Option 1:

$datetime = (new DateTime('now'))->format('U');
$datetime_min = (new DateTime('today - 4 weeks')->format('U');

Option 2:

$filetime = new DateTime(@filemtime($product));
if (filetime > $datetime_min) {}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement