2012-02-02 25 views
2

私はフォルダをループして、その中のすべてのファイルを削除するスクリプトを探していますが、最新のもの(それぞれのファイルの名前はfilename_date('Y')_date('m')_date('d').extension)とマークされています。フォルダ内のすべてのファイルを削除しますが、最後のファイルは削除しますか?

私はスタック上に、ここで、このスクリプトを発見した:

if ($handle = opendir('/path/to/your/folder')) 
{ 
    $files = array(); 
    while (false !== ($file = readdir($handle))) 
    { 
     if (!is_dir($file)) 
     { 
      // You'll want to check the return value here rather than just blindly adding to the array 
      $files[$file] = filemtime($file); 
     } 
    } 

    // Now sort by timestamp (just an integer) from oldest to newest 
    asort($files, SORT_NUMERIC); 

    // Loop over all but the 5 newest files and delete them 
    // Only need the array keys (filenames) since we don't care about timestamps now as the array will be in order 
    $files = array_keys($files); 
    for ($i = 0; $i < (count($files) - 5); $i++) 
    { 
     // You'll probably want to check the return value of this too 
     unlink($files[$i]); 
    } 
} 

以上これが最後の5つ以外のものを削除します。これは良い方法ですか?または、別の方法、より単純なまたはより良いものがありますか?

答えて

2

これは機能します。私はそれを行う簡単な方法があるとは思わない。さらに、あなたのソリューションは実際には非常にシンプルです。

1

私は良い解決策だと思います。ただ私は、これは古いです知っているループに

を変更していますが、最新の EDIT ソートが古い

0

にちょうど最初のファイルを保存し、アレイのすべての残りの部分を削除することができるように、あなたは下降モードで配列をソートするforループを避けることができでもこのようにすることもできます

$directory = array_diff(scandir(pathere), array('..', '.')); 
$files = []; 
foreach ($directory as $key => $file) { 
    $file = pathere.$file; 
    if (file_exists($file)) { 
     $name = end(explode('/', $file)); 
     $timestamp = preg_replace('/[^0-9]/', '', $name); 
     $files[$timestamp] = $file; 
    } 
} 
// unset last file 
unset($files[max(array_keys($files))]); 
// delete old files 
foreach ($files as $key => $dfiles) { 
    if (file_exists($dfiles)) { 
     unlink($dfiles); 
    } 
} 
関連する問題