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

时间:2013-10-04 11:46:32

标签: php

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

2 个答案:

答案 0 :(得分:2)

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

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'];
}

答案 1 :(得分:0)

您需要使用 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));
}
?>