简体   繁体   中英

get all files in subdirectories

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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