2012-02-02 3 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]); 
    } 
} 

이 위의 마지막 다섯 아무것도하지만 삭제합니다. 이것이 좋은 방법일까요? 아니면 다른 방법, 더 간단하거나 더 좋은 방법이 있습니까?

답변

2

그건 그렇습니다. 나는 그것을하는 더 쉬운 방법이 있다고 생각하지 않는다. 또한 솔루션은 실제로 매우 간단합니다.

1

나는 좋은 해결책이라고 생각합니다. 당신이 배열의 나머지는 모두 최신에서

0

내가 알고이 나이가 나이에 단지 첫 번째 파일을 편집 종류의 저장을 삭제할 수 있도록 단지 루프

을 수정하지만 당신은이 하강 모드에서 배열을 정렬 루프 피할 수 하지만 너도 이렇게 할 수있어.

$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); 
    } 
} 
관련 문제