2016-11-23 8 views
0

디렉토리에 여러 (아카이브 된) 백업 파일이 있습니다. "backup-"로 시작하는 파일 이름.모든 파일을 지우지 만 최신 파일을 유지하십시오.

이전보다 7 일 이상 오래된 파일을 모두 삭제하고 싶지만 항상 하나의 파일 (최신 파일)이 있어야합니다. 그렇지 않으면 백업 파일이 더 이상 없습니다.

7 일 이상 된 모든 파일을 삭제하는 소스 코드가 있지만 (아래 참조), 디렉토리에 최신 파일을 항상 보관하는 방법은 무엇입니까? 따라서, 남은 사람은 7 일 이상 될 수 있습니다 (가장 최신 인 경우).

$bu_days=7; 
$files="backup*.tar.gz"; 

foreach(glob($filter) as $fd) { 
    if(is_file($fd) && time() - filemtime($fd) >= $bu_days*24*60*60) {unlink($fd);} 
} 
+0

그냥 파일을 계산하고 휴식; foreach는 단지 하나의 파일이 남아있을 때입니까? – Thomas

+0

삭제하기 전에 몇 가지 테스트를해야합니다. – RST

+1

질문이 해결 된 경우 적절한 답을 해결책으로 표시하십시오 (질문 제목에 '해결'추가하는 대신). –

답변

1

당신은 날짜별로 파일을 정렬 할 수 있습니다, 다음 첫 번째 제외한 모든을 삭제 :

$bu_days=7; 
$files="backup*.tar.gz"; 

//retrieve all files 
$theFiles = glob($files); 

//combine the date as a key for each file 
$theFiles = array_combine(array_map("filemtime", $theFiles), $theFiles); 

//sort them, descending order 
krsort($theFiles); 

//remove the first item 
unset($theFiles[0]); 

foreach($theFiles as $fd){ 
    if(is_file($fd) && time() - filemtime($fd) >= $bu_days*24*60*60) {unlink($fd);} 
} 
+0

감사합니다 Veve, 당신의 소스에 작은 오류가 있다고 생각합니다 : "foreach (theFiles as $ fd) {"에서 theFiles 앞에 $를 잊어 버렸습니다. –

+1

대신 "first = true"등등을 사용할 수 있습니다. 배열에서 제거하는 "unset (array [0])"을 사용할 수 있습니다. –

+0

@ni_hao 맞습니다. 팁과 더 나은 내용으로 내 대답을 편집했습니다. 각 파일에 대해 파일 날짜에 여러 번 액세스 할 필요가없는 솔루션입니다. – Veve

0

업데이트 소스 :

//declare after how many days files are too old 
$bu_days=7; 

//declare how many files always should be kept        
bu_min=3; 

//define file pattern 
$files="backup*.tar.gz"; 

//retrieve all files 
$theFiles = glob($files); 

//combine the date as a key for each file 
$theFiles = array_combine($theFiles, array_map("filemtime", $theFiles)); 

//sort array, descending order (newest first) 
arsort($theFiles); 

//return subset of the array keys 
$f = array_keys($theFiles); 

// keep the first $bu_min files of the array, by deleting them from the array 
$f = array_slice($theFiles, $bu_min); 

// delete every file in the array which is >= $bu_days days 
foreach($theFiles as $fd){ 
    if(is_file($fd) && time() - filemtime($fd) >= $bu_days*24*60*60) {unlink($fd);} 
} 
관련 문제