2013-02-12 2 views
1

여러 하위 디렉토리가있는 디렉토리가 있다고 가정합니다. 이제 모든 하위 디렉토리를 검색하여 이름이 인 abc.php 인 파일을 찾은 다음이 파일이있는 모든 위치에서이 파일을 삭제하는 방법은 무엇입니까? 특정 하위 파일 이름이있는 모든 하위 디렉토리에서 PHP로 삭제

나는이 같은 일을 시도 -

$oAllSubDirectories = scandir(getcwd()); 
foreach ($oAllSubDirectories as $oSubDirectory) 
{ 
    //Delete code here 
} 

을하지만이 코드는 서브 디렉토리 안에 디렉토리를 확인하지 않습니다. 어떤 생각이든 어떻게 할 수 있습니까?

+0

HTTP : //www.kerstner합니다./ja/2011/12/recursively-delete-files-using-php/ – Stefan

답변

3

일반적으로 코드를 함수 안에 넣고 재귀 적으로 만듭니다. 디렉토리를 만날 때 코드는 내용을 처리하기 위해 자신을 호출합니다. 이런 식으로 뭔가 :

function processDirectoryTree($path) { 
    foreach (scandir($path) as $file) { 
     $thisPath = $path.DIRECTORY_SEPARATOR.$file; 
     if (is_dir($thisPath) && trim($thisPath, '.') !== '') { 
      // it's a directory, call ourself recursively 
      processDirectoryTree($thisPath); 
     } 
     else { 
      // it's a file, do whatever you want with it 
     } 
    } 
} 

이 특정한 경우에 당신이 할 필요가 없습니다 PHP는 기성품이 자동으로 수행하는 RecursiveDirectoryIterator을 제공하기 때문에 :

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(getcdw())); 
while($it->valid()) { 
    if ($it->getFilename() == 'abc.php') { 
     unlink($it->getPathname()); 
    } 
    $it->next(); 
} 
+0

@Jon을 회신 해 주셔서 감사합니다. 단 하나의 질문입니다 .. 위의 코드에서 ** DS **는 무엇입니까 ($ path.DS. $ 파일)? – skos

+0

@SachynKosare : 사실 그것은 내 실수였습니다. 나는 ['DIRECTORY_SEPARATOR'] (http://php.net/manual/en/dir.constants.php)을 의미했습니다. 내장 된 PHP 상수입니다. – Jon

+0

고맙습니다. @ 존, 이것이 내가 원하는 모든 것입니다. RecursiveIteratorIterator는 완벽하게 작동합니다 .. – skos

관련 문제