Jump to content

Help with scandir function


herghost

Recommended Posts

Hi all

 

I am using this function to list all files and folders within a directory

 

function getFilesFromDir($dir) { 

  $files = array(); 
  if ($handle = opendir($dir)) { 
    while (false !== ($file = readdir($handle))) { 
        if ($file != "." && $file != "..") { 
            if(is_dir($dir.'/'.$file)) { 
                $dir2 = $dir.'/'.$file; 
                $files[] = getFilesFromDir($dir2); 
            } 
            else { 
              $files[] = $dir.'/'.$file; 
            } 
        } 
    } 
    closedir($handle); 
  } 

  return array_flat($files); 
} 

function array_flat($array) { 

  foreach($array as $a) { 
    if(is_array($a)) { 
      $tmp = array_merge($tmp, array_flat($a)); 
    } 
    else { 
      $tmp[] = $a; 
    } 
  } 

  return $tmp; 
} 

 

When I call the function I give the dir as a variable, however if the dir I want is a sub-dir of a current dir then the list starts from the main dir

 

Basically say my file test.html is contained here files/test/test.html, the input I need to give is files/test/. This would then output in the array ->files/test/test.html. What I would like the output to be is test/test.html. How do I edit my recursive function to start from the final folder in the input?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/255378-help-with-scandir-function/
Share on other sites

function getFilesFromDir($dir) {

 

  $files = array();

  if ($handle = opendir($dir)) {

    while (false !== ($file = readdir($handle))) {

        if ($file != "." && $file != "..") {

            if(is_dir($dir.'/'.$file)) {

                $dir2 = $dir.'/'.$file;

//                $files[] = getFilesFromDir($dir2);

                $files = getFilesFromDir($dir2) + $files; // array union operator

            }

            else {

              $files[] = $dir.'/'.$file;

            }

        }

    }

    closedir($handle);

try this:

function ListFiles($dir) {

    if($dh = opendir($dir)) {

        $files = Array();
        $inner_files = Array();

        while($file = readdir($dh)) {
            if($file != "." && $file != ".." && $file[0] != '.') {
                if(is_dir($dir . "/" . $file)) {
                    $inner_files = ListFiles($dir . "/" . $file);
                    if(is_array($inner_files)) $files = array_merge($files, $inner_files); 
                } else {
                    array_push($files, $dir . "/" . $file);
                }
            }
        }

        closedir($dh);
        return $files;
    }
}

example:

foreach(Listfile('path to directory') as $key=>file) { echo $file."<br />"}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.