2014-10-09 74 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; 
    } 
} 
相关问题