在目录中添加最新文件

Gra*_*ton 34 php

如何获取最新的文件名或添加到目录中的文件路径?

kky*_*kyy 56

$path = "/path/to/my/dir"; 

$latest_ctime = 0;
$latest_filename = '';    

$d = dir($path);
while (false !== ($entry = $d->read())) {
  $filepath = "{$path}/{$entry}";
  // could do also other checks than just checking whether the entry is a file
  if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
    $latest_ctime = filectime($filepath);
    $latest_filename = $entry;
  }
}

// now $latest_filename contains the filename of the file that changed last
Run Code Online (Sandbox Code Playgroud)

  • [ctime不是创作时间](http://userprimary.net/posts/2007/11/18/ctime-in-unix-means-last-change-time-not-create-time/) (9认同)
  • 正如其他人在其他答案中提到的那样......应该使用`filemtime`而不是`filectime`.a)跨平台更广泛地支持它.b)它返回您可能想要的内容:文件上次修改的时间 (2认同)

NDM*_*NDM 6

$dir = dirname(__FILE__).DIRECTORY_SEPARATOR;
$lastMod = 0;
$lastModFile = '';
foreach (scandir($dir) as $entry) {
    if (is_file($dir.$entry) && filectime($dir.$entry) > $lastMod) {
        $lastMod = filectime($dir.$entry);
        $lastModFile = $entry;
    }
}
Run Code Online (Sandbox Code Playgroud)


Ole*_*sen 5

filectime用于更改chmod值之类的元数据.filemtime用于实际内容更改.