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);
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');