Emiel
Emiel

Reputation: 33

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?

Upvotes: 1

Views: 927

Answers (4)

Paul Allsopp
Paul Allsopp

Reputation: 741

Don't use glob, it's inefficient to fetch results you'll never use, especially if the directory was huge.

Try instead:

exec("find $filePath -mtime -$days | rev | cut -d/ -f1 | rev", $results);

Because we don't always know the number of path separators, use cut with rev and the file is always the first entry.

Upvotes: 0

jspit
jspit

Reputation: 7703

You can use array_filter() for this problem.

$tsLimit = strtotime('-2 Month');
$file_pattern = ..//your file pattern

$files = array_filter(
  glob($file_pattern), 
  function($val) use($tsLimit){
    return filemtime($val) > $tsLimit;
  }
);

Upvotes: 1

azibom
azibom

Reputation: 1944

Just try this script

<?php

$to = date("Y-m-d H:i:s");
$from = date('Y-m-d H:i:s', strtotime("-100 days"));

getAllFilesInDirectoryWithDateRange("*.*", $sdf, $today);

function getAllFilesInDirectoryWithDateRange($filePattern, $from, $to) {
    foreach (glob($filePattern) as $filename) {
        if (date("Y-m-d H:i:s", filemtime($filename)) >= $from &&
            date("Y-m-d H:i:s", filemtime($filename)) <= $to) {
                echo "$filename" . "\n";
        }
    }
}

output

test1.txt
test2.txt
test3.txt
test4.txt
test5.txt

You can use getAllFilesInDirectoryWithDateRange function and get all file names in a directory
In this function I use filemtime to get the time and then check the threshold like this

date("Y-m-d H:i:s", filemtime($filename)) >= $from && 
date("Y-m-d H:i:s", filemtime($filename)) <= $to

Upvotes: 0

John Conde
John Conde

Reputation: 219914

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) {}

Upvotes: 2

Related Questions