php遍历一个文件夹下的所有目录及文件
作者: 来源: 时间:2010-11-13 11:39:31 点击:
47 次
在面试中我们经常遇到这个题目:php遍历一个文件夹下的所有文件和子文件夹。
这个题目有好多种解决方法。但大致思路都一样。采用递归。
1. $path = './filepath';
2. function getfiles($path)
3. {
4. if(!is_dir($path)) return;
5. $handle = opendir($path);
6. while( false !== ($file = readdir($handle)))
7. {
8. if($file != '.' && $file!='‘)
9. {
10. $path2= $path.'/'.$file;
11. if(is_dir($path2))
12. {
13. echo '
14. ';
15. echo $file;
16. getfiles($path2);
17. }else
18. {
19. echo '
20. ';
21. echo $file;
22. }
23. }
24. }
25. }
26.
27. print_r( getfiles($path));
28.
29. echo '
30. <HR>';
31.
32. function getdir($path)
33. {
34. if(!is_dir($path)) return;
35. $handle = dir($path);
36. while($file=$handle->read())
37. {
38. if($file!='.' && $file!='’)
39. {
40. $path2 = $path.'/'.$file;
41. if(is_dir($path2))
42. {
43. echo $file.“\t”;
44. getdir($path2);
45. }else
46. {
47. echo $file.'
48. ';
49. }
50. }
51. }
52. }
53. getdir($path);
54.
55. echo '
56. <HR>';
57.
58. function get_dir_scandir($path){
59.
60. $tree = array();
61. foreach(scandir($path) as $single){
62. if($single!='.' && $single!='‘)
63. {
64. $path2 = $path.'/'.$single;
65. if(is_dir($path2))
66. {
67. echo $single.“
68. \r\n”;
69. get_dir_scandir($path2);
70. }else
71. {
72. echo $single.“
73. \r\n”;
74. }
75. }
76. }
77. }
78. get_dir_scandir($path);
79.
80. echo '
81. <HR>';
82.
83. function get_dir_glob(){
84. $tree = array();
85. foreach(glob('./curl/*’) as $single){
86. echo $single.“
87. \r\n”;
88. }
89. }
90. get_dir_glob();
91.
92. echo '
93. <HR>';
94. function myscandir($path)
95. {
96. if(!is_dir($path)) return;
97. foreach(scandir($path) as $file)
98. {
99. if($file!='.' && $file!='‘)
100. {
101. $path2= $path.'/'.$file;
102. if(is_dir($path2))
103. {
104. echo $file;
105. myscandir($path2);
106. }else
107. {
108. echo $file.'
109. ';
110. }
111. }
112. }
113. }
114.
115. myscandir($path);
116.
117. echo '
118. <HR>';
119.
120. function myglob($path)
121. {
122. $path_pattern = $path.'/*';
123. foreach(glob($path_pattern) as $file)
124. {
125. if(is_dir($file))
126. {
127. echo $file;
128. myscandir($file);
129. }else
130. {
131. echo $file.'
132. ';
133. }
134. }
135. }
136.
137. myglob($path);