• Home
  • About
  • Who Am I?
  •  

    Get File Names from Directories and Sub Directories in PHP

    These are a couple of functions i use to get the directories and files from a specific folder. This is a recursive function and brings the sub directories as well. Returns an array.

    First param is the folder path to start
    Second param tells the function if it needs to bring the files inside the folder
    Third param tells if the function needs to bring sub directories as well.

    $folders = array();
    folderlist(”testserver” , true , true);
    print_r($folders);
    
    function folderlist($folder_path = “” , $getfiles = true , $tree=true){
      global $folders;
      $handle = opendir($folder_path.”/.”);
      while (false !== ($file = readdir($handle))) {
       if ($file != “.” && $file != “..”) {
        if(is_dir($folder_path.”/”.$file)){
        if($getfiles){
          $fileshere = filelist($folder_path.”/”.$file);
           $folders[] = array(”foldername” => $folder_path.”/”.$file  ,
                            “files” => $fileshere
                            );
         }else{
         $folders[] = array(”foldername” => $folder_path.”/”.$file);
         }
         if($tree) folderlist($folder_path.”/”.$file);
      }
     } } return $folders;
    }
    
    function filelist($folder_path){
      $files = array();
      $handle = opendir($folder_path.”/.”);
      while (false !== ($file = readdir($handle))) {
        if ($file != “.” && $file != “..”) {
         if(!is_dir($folder_path.”/”.$file)){
          $files[] = $folder_path.”/”.$file;
         }
        }
      }
      return $files;
    }

     


    One Response to “Get File Names from Directories and Sub Directories in PHP”

    1. Gferrell Says:

      Are you using this as an import function?

      I have not been successful in getting this to work inline.

    Leave a Reply