Recursively Search within a directory for all folder paths

前提是你 提交于 2019-12-11 06:22:29

问题


I am trying to recursively search through a directory for all sub-directories within any directories of sub-directories. Basically all folders starting at the root directory, and I need to copy a file to all folders found as well as in the main root folder. How can I do this?

Here's what I have so far, but it needs to be recursive completely so that it gets all folders within that root, and folders within subs, and folders within that, neverending search, until there are no more folders left...

@copy($extendVars['dir'] . '/index.php', $real_extendpath . '/index.php');

$dh = @opendir($real_extendpath);
while (false !== ($obj = readdir($dh)))
{
    if ($obj == '.' || $obj == '..')
        continue;

    if (is_dir($real_extendpath . '/' . $obj))
        @copy($extendVars['dir'] . '/index.php', $real_extendpath . '/' . $obj . '/index.php');
}

closedir($dh);

回答1:


Recursing over the filesystem for only the directories can be super-easy using the RecursiveDirectoryIterator and friends from the Standard PHP Library (docs).

A basic example would look like

$directories = new RecursiveIteratorIterator(
    new ParentIterator(new RecursiveDirectoryIterator($directory_to_iterate)), 
    RecursiveIteratorIterator::SELF_FIRST);

foreach ($directories as $directory) {
    // Do your work here
}

For your particular needs, the // Do your work here could be as simple as the following snippet.

copy($extendedVars['dir'] . '/index.php', $directory . '/index.php');


来源:https://stackoverflow.com/questions/7938680/recursively-search-within-a-directory-for-all-folder-paths

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!