2009-09-29 67 views
27

如何獲取最新的文件名,或者是添加到目錄中的文件路徑的最新文件除?獲得目錄

回答

49
$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 
+8

[ctime並非創建時間] (http://userprimary.net/posts/2007/11/18/ctime-in-unix-means-last-change-time-not-create-time/) – kojiro 2012-01-12 21:46:55

+1

爲最快的搜索或掃描任何新的方法? – Muhaimin 2015-01-14 03:17:49

+0

@Muhaimin阿卜杜勒嘗試SCANDIR()〜PHP 5 – 2016-03-08 10:03:04

0

列舉所有目錄中的文件,讓每個filemtime(),和你做。

+1

我想你最好'filectime'。 – Gumbo 2009-09-29 07:17:26

+0

@Gumbo:爲什麼使用filectime而不是filemtime。我發現filemtime()在多種平臺上工作得更好,而filectime()似乎在所有Windows服務器上都不能正常工作。 – secretlm 2013-06-19 10:17:03

+1

@secretlm'filectime'可能不起作用,因爲它只有文件的創建時間,而不是修改時間 – FluorescentGreen5 2017-06-12 07:16:56

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; 
    } 
} 
+0

沒關係,我看你定吧:) – kkyy 2009-09-29 07:39:11

+0

這是早晨在這裏:) – NDM 2009-09-29 07:40:01

3
$dir = "/path/to/Your/dir";   
$pattern = '\.(zip|ZIP|pdf|PDF)$'; // check only file with these ext.   
$newstamp = 0;    
$newname = ""; 

if ($handle = opendir($dir)) {    
     while (false !== ($fname = readdir($handle))) {    
     // Eliminate current directory, parent directory    
     if (ereg('^\.{1,2}$',$fname)) continue;    
     // Eliminate other pages not in pattern    
     if (! ereg($pattern,$fname)) continue;    
     $timedat = filemtime("$dir/$fname");    
     if ($timedat > $newstamp) { 
      $newstamp = $timedat; 
      $newname = $fname; 
      } 
     } 
     } 
closedir ($handle); 

// $newstamp is the time for the latest file 
// $newname is the name of the latest file 
// print last mod.file - format date as you like    
print $newname . " - " . date("Y/m/d", $newstamp); 
+0

這將使用折舊功能:額日格() – 2014-08-01 15:42:29

5

filectime用於像chmod值這樣的元數據發生更改時。 filemtime用於實際內容更改。

0

我與PHP 5的解決方案:

$dir = "/path/to/Your/dir"; 
$arraydir =scandir($dir, 1); 
echo "arraydir 0: " . $arraydir[0] . "<br/>"; // 1. new file 
echo "arraydir 1: " . $arraydir[1] . "<br/>"; // 2. new file 
echo "arraydir elements: " . count($arraydir) . "<br/>"; 

(搜索詞DE:neuste UND zweitneuste Datei EINES Ordners anzeigen MIT PHP)