Home >Backend Development >PHP Tutorial >PHP gets all files (including subdirectories) in the specified directory, _PHP tutorial
PHP gets all the files (including subdirectories) in the specified directory
The test environment is under Linux. If you want to use Windows, please correct the directory path search method in $new_dir
<?<span>php function get_file_list($dir) { </span><span> $file_list </span>=<span> array(); $file_dir_list </span>=<span> array(); $dir_list </span>= scandir($dir); <span>//</span><span>查找目录 </span> <span>foreach</span> ($dir_list <span>as</span><span> $r) { </span><span>if</span> ($r == <span>'</span><span>.</span><span>'</span> || $r == <span>'</span><span>..</span><span>'</span><span>) { </span><span>continue</span><span>; } $new_dir </span>= $dir . <span>'</span><span>/</span><span>'</span><span> . $r; </span><span>if</span><span> (is_dir($new_dir)) {</span><span> $file_dir </span>=<span> get_file_list($new_dir); $file_dir_list </span>=<span> array_merge($file_dir_list, $file_dir); } </span><span>else</span><span> { $file_list[] </span>=<span> $new_dir; } } </span><span>return</span><span> array_merge($file_list, $file_dir_list); } $file_list </span>= get_file_list(<span>'</span><span>.</span><span>'</span><span>); print_r($file_list);</span>
The scandir() function returns an array containing the files and directories in the specified path.
If successful, return an array, if failed, return false. If directory is not a directory, returns Boolean false and generates an E_WARNING level error.
scandir(directory,sort,context)
参数 | 描述 |
---|---|
directory | 必需。规定要扫描的目录。 |
sort | 可选。规定排列顺序。默认是 0 (升序)。如果是 1,则为降序。 |
context | 可选。规定目录句柄的环境。context 是可修改目录流的行为的一套选项。 |
<?<span>php print_r(scandir(</span><span>"</span><span>images</span><span>"</span><span>)); </span>?>
Output:
<span>Array ( [</span><span>0</span>] =><span> . [</span><span>1</span>] =><span> .. [</span><span>2</span>] =><span> dog.jpg [</span><span>3</span>] =><span> house.jpg [</span><span>4</span>] =><span> logo.gif )</span>