2013-02-12 134 views
1

假設有一個目錄中有許多子目錄。現在我該如何掃描所有子目錄才能找到名稱爲abc.php的文件,並在找到該文件的任何地方刪除該文件。在PHP中刪除所有子目錄中的文件名的特定文件

我試圖做這樣的事情 -

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

但這代碼不檢查子目錄裏面的目錄。任何想法我怎麼能做到這一點?

+0

HTTP://www.kerstner。 at/en/2011/12/recursively-delete-files-using-php/ – Stefan 2013-02-12 09:30:48

回答

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 2013-02-12 10:18:32

+0

@SachynKosare:其實這是我的錯誤。我的意思是['DIRECTORY_SEPARATOR'](http://php.net/manual/en/dir.constants.php)。這是一個內置的PHP常量。 – Jon 2013-02-12 10:21:38

+0

非常感謝@Jon,這是我想要的.. RecursiveIteratorIterator完美地工作.. – skos 2013-02-12 10:26:15

相關問題