2014-10-09 71 views
0

其實iam通過php在我創建的導出文件夾中轉儲數據庫文件。 在這裏,我想只保留最新的十個sql文件在導出文件夾類的FIFO方式。 我不想過度填充文件夾,並想限制它十個最新的文件。 如何做到這一點?如何限制一個文件夾的最大文件數

+1

使用與轉儲數據庫文件相同的代碼刪除第11個文件。 – 2014-10-09 06:26:58

回答

0

首先抓住所有的文件使用glob例如,然後確定是否有十個或目錄中有更多文件。之後,檢查mtime(修改時間),並刪除最舊的一個。

$file_pattern = '/path/to/directory/and/files/*'; 
$filenames = glob($file_pattern); 

if (count($filenames) > 9) { 
    // While there are ten or more files. 
    while (count(glob($file_pattern)) > 9) { 
     $oldest_file = null; 

     // Grab the unix timestamp of *now*, as filemtime returns a unix timestamp too. 
     $current_oldest_time = time(); 

     foreach ($filenames as $filename) { 
      $filetime = filemtime($filename); 

      if ($filetime < $current_oldest_time) { 
       $current_oldest = $filetime; 
       $oldest_file = $filename; 
      } 
     } 

     // After the foreach you'll have the filename of the oldest file (remove it),: 
     unlink($oldest_file); 

     // Or null if something went wrong (break out of the loop): 
     break; 
    } 
} 
相關問題