Home  >  Article  >  Backend Development  >  PHP implementation code to obtain all directories and files contained in a directory

PHP implementation code to obtain all directories and files contained in a directory

WBOY
WBOYOriginal
2016-07-25 08:57:48860browse
  1. /**
  2. * Get all directories and files contained in the input directory
  3. * Return as an associative array
  4. * edit: bbs.it-home.org
  5. */
  6. function deepScanDir($dir)
  7. {
  8. $fileArr = array();
  9. $dirArr = array();
  10. $dir = rtrim($dir, '//');
  11. if(is_dir($dir)){
  12. $dirHandle = opendir($dir);
  13. while(false !== ($fileName = readdir($dirHandle))){
  14. $subFile = $dir . DIRECTORY_SEPARATOR . $fileName;
  15. if(is_file($subFile)){
  16. $fileArr[] = $subFile;
  17. } elseif (is_dir($subFile) && str_replace('.', '', $fileName)!=''){
  18. $dirArr[] = $subFile;
  19. $arr = deepScanDir($subFile);
  20. $dirArr = array_merge($dirArr, $arr['dir']);
  21. $fileArr = array_merge($fileArr, $arr['file']);
  22. }
  23. }
  24. closedir($dirHandle);
  25. }
  26. return array('dir'=>$dirArr, 'file'=>$fileArr);
  27. }
  28. //示例
  29. $dir = '/var/htdocs/w4/article';
  30. $arr = deepScanDir($dir);
  31. print_r($arr);
  32. /**
  33. * Get all files contained in the input directory
  34. * Return as an array
  35. * author: flynetcn
  36. */
  37. function get_dir_files($dir)
  38. {
  39. if (is_file($dir)) {
  40. return array($dir);
  41. }
  42. $files = array();
  43. if (is_dir($dir) && ($dir_p = opendir($dir))) {
  44. $ds = DIRECTORY_SEPARATOR;
  45. while (($filename = readdir($dir_p)) !== false) {
  46. if ($filename=='.' || $filename=='..') { continue; }
  47. $filetype = filetype($dir.$ds.$filename);
  48. if ($filetype == 'dir') {
  49. $files = array_merge($files, get_dir_files($dir.$ds.$filename));
  50. } elseif ($filetype == 'file') {
  51. $files[] = $dir.$ds.$filename;
  52. }
  53. }
  54. closedir($dir_p);
  55. }
  56. return $files;
  57. }
复制代码


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