在PHP中删除所有子目录中的文件名的特定文件

问题描述:

假设有一个目录中有许多子目录。现在我该如何扫描所有子目录才能找到名称为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

一般来说,你把代码放在一个函数中,并使其递归:当它遇到一个目录时,它会自己调用它来处理它的内容。事情是这样的:

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