Summary of methods for traversing folders in PHP

黄舟
Release: 2023-03-06 11:06:02
Original
1973 people have browsed it

In general PHP interviews, many people will ask this question: Write a method that can traverse all files and folders in a specified folder. Let's summarize it below, I hope it can be helpful to everyone

php traverses the folder, which is often needed

/*Get all files*/

function get_all_files( $path ){
  $list = array();
  foreach( glob( $path . '/*') as $item ){
    if( is_dir( $item ) ){
     $list = array_merge( $list , get_all_files( $item ) );
    }
    else{
     $list[] = $item;
    }
  }
  return $list;
}
Copy after login

/*Get all files, only one level of directory files*/

function get_my_files( $path ){
  $list = array();
  foreach( glob( $path . '/*') as $item ){
    if( is_dir( $item ) ){
     $list[] = $item;
    }
  }
  return $list;
}
Copy after login

php Traverse the folder Enhanced version

/*Get all files with time*/

function get_all_files_time( $path ){
 clearstatcache();
  $list = array();
 
  foreach( glob( $path . '/*') as $item ){
    if( is_dir( $item ) ){
  $list = array_merge( $list , get_all_files_time( $item ) );
 
    }
    else{
 
  $list[$item] = ftime(fileatime($item)); //fileatime 访问时间 fileatime 访问时间 filemtime 修改时间
 
 
    }
  }
  return $list;
}
Copy after login

/*Get all files with time*/

function get_all_files_mtime( $path ){
 clearstatcache();
  $list = array();
 
  foreach( glob( $path . '/*') as $item ){
    if( is_dir( $item ) ){
  $list = array_merge( $list , get_all_files_mtime( $item ) );
 
    }
    else{
 
  $list[$item] = ftime(filemtime($item)); //fileatime 访问时间 fileatime 访问时间 filemtime 修改时间
 
 
    }
  }
  return $list;
}
Copy after login

The above is a summary of the methods of traversing folders in PHP. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!