Home > Backend Development > PHP Tutorial > PHP code to traverse all files and sub-files in a folder

PHP code to traverse all files and sub-files in a folder

不言
Release: 2023-04-02 11:14:02
Original
3678 people have browsed it

This article mainly introduces the code for php to traverse all files and sub-files in a folder. It has certain reference value. Now I share it with you. Friends in need can refer to it

php traversal All files and sub-files under a folder

 1 <?php
 2 /** 
 3  * 将读取到的目录以数组的形式展现出来 
 4  * @return array 
 5  * opendir() 函数打开一个目录句柄,可由 closedir(),readdir() 和 rewinddir() 使用。 
 6  * is_dir() 函数检查指定的文件是否是目录。 
 7  * readdir() 函数返回由 opendir() 打开的目录句柄中的条目。 
 8  * @param array $files 所有的文件条目的存放数组 
 9  * @param string $file 返回的文件条目
 10  * @param string $dir 文件的路径
 11  * @param resource $handle 打开的文件目录句柄
 12  */
 13 function my_scandir($dir)
 14 {
 15     //定义一个数组
 16     $files = array();
 17     //检测是否存在文件
 18     if (is_dir($dir)) {
 19         //打开目录
 20         if ($handle = opendir($dir)) {
 21             //返回当前文件的条目
 22             while (($file = readdir($handle)) !== false) {
 23                 //去除特殊目录
 24                 if ($file != "." && $file != "..") {
 25                     //判断子目录是否还存在子目录
 26                     if (is_dir($dir . "/" . $file)) {
 27                         //递归调用本函数,再次获取目录
 28                         $files[$file] = my_scandir($dir . "/" . $file);
 29                     } else {
 30                         //获取目录数组
 31                         $files[] = $dir . "/" . $file;
 32                     }
 33                 }
 34             }
 35             //关闭文件夹
 36             closedir($handle);
 37             //返回文件夹数组
 38             return $files;
 39         }
 40     }
 41 }
 42 
 43 echo "<pre class="brush:php;toolbar:false">";
 44 print_r(my_scandir("./aa")); //电脑的文件路径即可
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

php method to calculate the relative path of two files

The above is the detailed content of PHP code to traverse all files and sub-files in a folder. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template