如何使用具有最小文件日期filemtime的 PHP glob()?

问题描述

我想使用 PHP glob 函数获取一系列文件,但不超过一个月(或其他指定的日期范围)。

我当前的代码

$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; }

这会返回一个错误

注意:DateTime 类的对象无法转换为 int

我认为它仍然为我提供了该文件夹中所有文件的结果。所以我的方法可能完全错误

我怎样才能使这段代码工作,所以我只有一个数组,其中的文件不早于指定日期?

解决方法

filemtime() returns a Unix timestamp 是一个整数。 DateTime 对象具有可比性,但只能相互比较。您需要将它们转换为 Unix 时间戳或将 filemtime() 的结果转换为 DateTime 对象。

选项 1:

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

选项 2:

$filetime = new DateTime(@filemtime($product));
if (filetime > $datetime_min) {}
,

试试这个脚本

<?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";
        }
    }
}

输出

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

您可以使用getAllFilesInDirectoryWithDateRange函数获取目录中的所有文件名
在这个函数中,我使用 filemtime 来获取时间,然后像这样检查阈值

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

您可以使用 array_filter() 解决此问题。

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

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