php Get all files and directories under the directory (multiple methods) (recommended)

  • 2021-12-11 07:08:56
  • OfStack

Get all subfiles and subdirectories in a directory


function getDirContent($path){
  if(!is_dir($path)){
    return false;
  }
  //readdir Method 
  /* $dir = opendir($path);
  $arr = array();
  while($content = readdir($dir)){
    if($content != '.' && $content != '..'){
      $arr[] = $content;
    }
  }
  closedir($dir); */

  //scandir Method 
  $arr = array();
  $data = scandir($path);
  foreach ($data as $value){
    if($value != '.' && $value != '..'){
      $arr[] = $value;
    }
  }
  return $arr;
}

The following three methods are to get all directories (including subdirectories and descendants) and files under a certain directory until the innermost layer

Method 1


function searchDir($path,&$files){

  if(is_dir($path)){

    $opendir = opendir($path);

    while ($file = readdir($opendir)){
      if($file != '.' && $file != '..'){
        searchDir($path.'/'.$file, $files);
      }
    }
    closedir($opendir);
  }
  if(!is_dir($path)){
    $files[] = $path;
  }
}
// Get the directory name 
function getDir($dir){
  $files = array();
  searchDir($dir, $files);
  return $files;
}
$filenames = getDir('lss');

foreach ($filenames as $value){
  echo $value.'<br/>';
} 

Method 2:


function getDir($path){

  if(is_dir($path)){

    $dir = scandir($path);
    foreach ($dir as $value){
      $sub_path =$path .'/'.$value;
      if($value == '.' || $value == '..'){
        continue;
      }else if(is_dir($sub_path)){
        echo ' Directory name :'.$value .'<br/>';
        getDir($sub_path);
      }else{
        //.$path  You can omit and output the file name directly 
        echo '  Bottom level file : '.$path. ':'.$value.' <hr/>';
      }
    }
  }
}
$path = 'lss';
getDir($path); 

Method 3:


function getDir($path){
  $arr = array();
    $arr[] = $path;
  if(is_file($path)){

  }else{
    if(is_dir($path)){
      $data = scandir($path);
      if(!empty($data)){
        foreach ($data as $value){
          if($value != '.' && $value != '..'){
            $sub_path = $path."/".$value;
            $temp = getDirContent($sub_path);
            $arr = array_merge($temp,$arr);
          }          
        }

      }
    }
  }

  return $arr;
}
$path = 'lss';
var_dump(getDir($path));

Related articles: