PHP 获取给定目录中最新保存的文件


PHP get the newest saved file in a given directory

我有一个文件夹保存在特定目录中,其中包含一些上传的图像,通过使用php,如何使用其路径访问此文件夹并返回此文件夹中最新添加(上传)的图像?

您必须扫描整个目录并找到最新文件:

function getLatestFile($directoryPath) {
    $directoryPath = rtrim($directoryPath, '/');
    $max = ['path' => null, 'timestamp' => 0];
    foreach (scandir($directoryPath, SCANDIR_SORT_NONE) as $file) {
        $path = $directoryPath . '/' . $file;
        if (!is_file($path)) {
            continue;
        }
        $timestamp = filemtime($path);
        if ($timestamp > $max['timestamp']) {
            $max['path'] = $path;
            $max['timestamp'] = $timestamp;
        }
    }
    return $max['path'];
}

你需要使用filemtime()函数:

<?php
// outputs e.g.  somefile.txt was last modified: December 29 2002 22:16:23.
$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
?>