[英]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));
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.