3

I need to move all files from all subdirectories into one folder.

So I need to have all paths of the files. I found this code:

function recurseDir($dir) {
if(is_dir($dir)) {
    if($dh = opendir($dir)){
        while($file = readdir($dh)){

            if($file != '.' && $file != '..'){
                if(is_dir($dir . $file)){
                    recurseDir($dir . $file);
                }else{
                    foreach(glob($dir.'/*.*') as $file1) {
                        echo $file1."<br />\r\n";
                    }                        
                }
            }
        }
    }
    closedir($dh);         
    }
  }  

However somehow it prints prints all files the amount of times there are files in the folder.

Can someone see where I made the error?

EDIT:

The return after the echo worked for the duplication,however this goes only one subfolder deep so it stops after checking the first subfolder.

5

1 Answer 1

0

You're missing the directory separator ("/") in your function call.

Try this.

<?php
    function recurseDir($dir) {
        if(is_dir($dir)) {

            if($dh = opendir($dir)){
                while($file = readdir($dh)){
                    if($file != '.' && $file != '..'){

                        if(is_dir($dir. DIRECTORY_SEPARATOR . $file)){
                            recurseDir($dir .DIRECTORY_SEPARATOR. $file);
                        }else{
                            foreach(glob($dir.'/*.*') as $file1) {
                                echo $file1."<br />\r\n";
                            }
                        }
                    }
                }
            }
            closedir($dh);
        }
    }
1
  • This worked for the duplication however it only goes one folder deep, do you know what I'm missing? Oct 20, 2017 at 14:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.