Jump to content

Convert function to be Recursive


bdichiara

Recommended Posts

I've got a function that reads all files and folders in a directory given directory. I would like this to be recursive, so when it encounters a folder, it runs the function over again with the new folder (directory). Problem is, I didn't write this function, so I'm not exactly sure how to accomplish this.

 

function getFiles($path) {
   $files = array();
   $fileNames = array();
   $i = 0;
  
   if (is_dir($path)) {
       if ($dh = opendir($path)) {
           while (($file = readdir($dh)) !== false) {
               if ($file == "." || $file == "..") continue;
               $fullpath = $path . "/" . $file;
               $fkey = strtolower($file);
               while (array_key_exists($fkey,$fileNames)) $fkey .= " ";
               $a = stat($fullpath);
               $files[$fkey]['size'] = $a['size'];
               if ($a['size'] == 0) $files[$fkey]['sizetext'] = "-";
               else if ($a['size'] > 1024) $files[$fkey]['sizetext'] = (ceil($a['size']/1024*100)/100) . " K";
               else if ($a['size'] > 1024*1024) $files[$fkey]['sizetext'] = (ceil($a['size']/(1024*1024)*100)/100) . " MB";
               else $files[$fkey]['sizetext'] = $a['size'] . " bytes";
               $files[$fkey]['name'] = $file;
		   $newpath = (strstr($fullpath,"//")) ? str_replace("//","/",$fullpath) : $fullpath;
		   $files[$fkey]['fullpath'] = $newpath;
		   $files[$fkey]['ext'] = getExtension($file);
		   $files[$fkey]['type'] = filetype($newpath);
		   $files[$fkey]['mod_date'] = (filemtime($newpath)) ? date("n/j/Y",filemtime($newpath)) : '' ;
               $fileNames[$i++] = $fkey;
           }
           closedir($dh);
       } else die ("Cannot open directory:  $path");
   } else die ("Path is not a directory:  $path");
   sort($fileNames,SORT_STRING);
   $sortedFiles = array();
   $i = 0;
   foreach($fileNames as $f) $sortedFiles[$i++] = $files[$f];
  
   return $sortedFiles;
}

 

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/73061-convert-function-to-be-recursive/
Share on other sites

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.