Take the 2-minute tour ×

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);
    if ($obj == '.' || $obj == '..')

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

share|improve this question
You need to make a function out of this to call it recursive. –  str Oct 29 '11 at 11:49
ok, but how? I'm not seeing a way to do that. Is there a better way to do this other than using readdir? Isn't there like a RecursiveIterator function of some sort? Would that be better? If so, how to use that function is tricky for me also... –  SoLoGHoST Oct 29 '11 at 11:52
The manual is full of exmples. php.net/manual/en/function.scandir.php#105891 - Also RecursiveDirectoryIterator –  mario Oct 29 '11 at 11:53
possible duplicate of How to walk a directory recursively returning the full path in PHP? –  mario Oct 29 '11 at 11:55
It should be consent, that PHP example code with the @ operator should not be posted on SO. –  hakre Oct 29 '11 at 12:06

1 Answer 1

up vote 9 down vote accepted

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)), 

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');
share|improve this answer
Thanks, very useful! :) –  SoLoGHoST Nov 1 '11 at 1:40
You saved my day... thax –  Paresh Thummar Mar 29 '13 at 12:17

Your Answer


