简体   繁体   English

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

[英]Deleting A Specific FIle WIth Filename From All Sub-directories In PHP

Suppose there's a directory in which there are numerous sub-directories. 假设有一个目录,其中有许多子目录。 Now how can I scan all the subdirectories to find a file with name, say, abc.php and delete this file wherever its is found. 现在我如何扫描所有子目录以查找具有名称的文件,例如abc.php,并在找到它的任何地方删除该文件。

I tried doing something like this - 我尝试过这样的事情 -

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

But this code doesn't check directories inside the subdirectories. 但是这段代码不会检查子目录中的目录。 Any idea how can I do this ? 知道我该怎么办?

In general, you put the code inside a function and make it recursive: when it encounters a directory it calls itself in order to process its contents. 通常,您将代码放在函数中并使其递归:当遇到目录时,它会调用自身以处理其内容。 Something like this: 像这样的东西:

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
        }
    }
}

In this particular case you don't need to do that because PHP offers the ready-made RecursiveDirectoryIterator that does this automatically: 在这种特殊情况下,您不需要这样做,因为PHP提供了现成的RecursiveDirectoryIterator ,它自动执行此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM