Home > Article > Backend Development > Summary of methods for traversing folders in PHP
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; }
/*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; }
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; }
/*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; }
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)!