Home  >  Article  >  Backend Development  >  PHP small example of traversing files and folders

PHP small example of traversing files and folders

WBOY
WBOYOriginal
2016-07-25 08:55:56811browse
  1. /**
  2. * Traverse files and folders
  3. * edit: bbs.it-home.org
  4. * 2013/10/12
  5. */
  6. function list_dir($dirpath){
  7. //Determine whether the last character of the path is a backslash, if not, add one
  8. if( $dirpath[strlen($dirpath)-1] !='\'){ $dirpath.='\';}
  9. //Declare a static variable array, so that the value of the array will still exist every time it is called recursively
  10. static $result_array = array();
  11. //Determine whether the given directory is a directory
  12. if(is_dir($dirpath)){
  13. //Get the current subdirectory and file name
  14. $file_dirs = scandir($dirpath);// scandir -- List the files and directories in the specified path
  15. //If there are two special directories, skip them
  16. foreach($file_dirs as $file){
  17. if($file == '.' || $file = ='..'){ continue;}
  18. if(is_dir($dirpath.$file)){
  19. //Directory, call recursively
  20. list_dir($dirpath.$file.'\');
  21. }else{
  22. //File, store it in the array
  23. array_push($result_array,$dirpath.$file);
  24. }
  25. }
  26. }
  27. return $result_array;
  28. }
  29. //Call function
  30. $array = list_dir('d:\ php5');
  31. foreach($array as $value){
  32. echo $value;
  33. echo'
    ';
  34. }
  35. ?>
Copy code


Statement:
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