如何获得文件夹中所有文件的最后修改日期并将其与特定日期进行比较?php


How do you get last modified dates of all files within a folder and compare it to a certain date? php

有没有人知道一种方法来获取文件夹内所有文件的最后修改日期,并将其与某个日期进行比较?

到目前为止我有这个。

<?php
    $lastmoddate = (date("Ymd", filemtime($file)));
    $todaysdate = date("Ymd", time());
    $result = array(); 
    $folder = ('uploaded_files/');     
    $handle = opendir($folder);
    foreach (glob("$folder/*") as $team){$sort[]= end(explode('/',$team));}
    while (false !==($file = readdir($handle)))
    {
        if ( $file != ".." && $file != "." )
        {
            $file = "uploaded_files/".$file ;
            if (!is_dir($file))
                $result[] = $file;
        } 
    }
    closedir($handle);

    foreach ($result as $file){
        if ($lastmoddate > $todaysdate){
            if (strpos($file, "+12:00") !==false){
                echo "$file".",".date ("h:i d/m/Y", filemtime($file))."'r'n"."<br/>";
            }
        }
    }
?>

这不起作用,因为$lastmoddate =给我日期1969 12 31。

到目前为止,我可以看到2不一致的东西在你的代码。

  1. 你只得到lastmoddate 一次,不是针对现有的文件,而是针对一些未定义的(尚未)$file

  2. 你的日期比较没有意义。比如说,即使你的文件今天被修改了,它的日期也不会大于今天的日期,所以,你所有的比较肯定会失败。至少用>===比较,不能用>

PHP的filemtime()(其内部基本上只是调用stat()并仅返回m-time值)一次只处理单个文件。

您已经在脚本中获得了glob()调用以获取文件名列表。将filemtime()调用放入该循环中以获取每个文件的mtime,并在其中进行比较。

您的代码不工作,因为您没有在初始filemtime()调用时为$file分配值,因此返回布尔值FALSE用于失败,它被转换为整数0用于date()格式化。您所在的时区为负gmt,因此将转换为稍微早于1970年1月1日的日期,即UTC时间0。

你需要的是:

foreach (glob("$folder/*") as $team) { 
    $lastmoddate = filemtime("$folder/$team");
    ... date stuff ...
    $sort[]= basename($team);
}