Home  >  Article  >  Backend Development  >  Introducing several methods of traversing directories and folders in PHP

Introducing several methods of traversing directories and folders in PHP

伊谢尔伦
伊谢尔伦Original
2017-07-08 11:47:031974browse

Introducing several phptraverse directories methods, you can traverse directories and files in directories, for your reference

Traverse directories or traverse files of specified types under directories, this is A child's shoe will inevitably be used when writing a program. PHP itself also provides many very useful functions. If you use them correctly, you will not go wrong.
This function can list all files in the specified directory (including subdirectories)

The code is as follows:

function getfiles($path){ 
foreach
(scandir($path) as $afile)
{
if($afile=='.'||$afile=='..') 
continue; 
if(is_dir($path.'/'.$afile)) 
{ 
getfiles($path.'/'.$afile); 
} else { 
echo $path.&#39;/&#39;.$afile.&#39;<br />&#39;; 
} 
} 
} //简单的demo,列出当前目录下所有的文件
getfiles(DIR);

scandir() returns all files in the specified directory An array composed of files and directories. In PHP, a very powerful function glob() is also provided. glob() has 2 parameters. The second parameter is optional and will be discussed later. Let’s look directly at how to traverse directories using glob().
It can be seen that '.' and '..' have been filtered out from the content returned by glob(), where * means traversing all files in the directory. Correspondingly, if it is changed to *.txt, all txt files in the directory will be traversed. Isn’t it very convenient? Its convenience is not limited to this. According to Yuan Fang, there is also a huge secret hidden in it. What is it? We will talk about it later. If you are interested, you can leave me a message to communicate.

The code is as follows:

function getfiles($path){ 
foreach(glob($path) as $afile){ 
if(is_dir($afile)) 
{ getfiles($afile.&#39;/*&#39;); } else { echo $afile.&#39;<br />&#39;; } 
} 
} //简单的demo,列出当前目录下所有的文件
getfiles(DIR);0


Since *.txt is used, all txt files in the directory will be traversed. If I want it to traverse certain types of files at the same time What about the file format? what to do? Some kid must have thought of using an array, and then quickly wrote it out and replaced it with {*.txt,*.jpg,*.zip,...}. Of course, they also quickly discovered that the program returned false and got nothing. . Don’t be disappointed, this involves the second optional parameter just mentioned. This parameter is used to change the behavior of glob. For details, you can check PHP Manual. I won’t go into details here, just Say a GLOB_BRACE, which is used to expand {a,b,c,...} to match 'a', 'b' or 'c',... The usage is as follows: foreach(glob($path.'/{*.txt,*.jpg,*.zip,...}', GLOB_BRACE) as $fileName){...}
As for the complete directory traversal Under all the specified file type functions, we can see the following example

Traverse all files in the folder and subfolders

The code is as follows:

<html>
    <body>
        <?php
            function traverse($path = &#39;.&#39;) {
                $current_dir = opendir($path);    //opendir()返回一个目录句柄,失败返回false
                while(($file = readdir($current_dir)) !== false) {    //readdir()返回打开目录句柄中的一个条目
                    $sub_dir = $path . DIRECTORY_SEPARATOR . $file;    //构建子目录路径
                    if($file == &#39;.&#39; || $file == &#39;..&#39;) {
                        continue;
                    } else if(is_dir($sub_dir)) {    //如果是目录,进行递归
                        echo &#39;Directory &#39; . $file . &#39;:<br>&#39;;
                        traverse($sub_dir);
                    } else {    //如果是文件,直接输出
                        echo &#39;File in Directory &#39; . $path . &#39;: &#39; . $file . &#39;<br>&#39;;
                    }
                }
            }
            traverse(&#39;xxtt&#39;);
        ?>
    </body>
</html>

Some commonly used examples

The code is as follows:

<?php
$dir="E:/video"; //这里输入其它路径
//PHP遍历文件夹下所有文件
$handle=opendir($dir."."); 
echo "文件:<br>";
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..") {
echo $file; //输出文件名
}
}
closedir($handle); 
?>

I used this code to traverse all files and help me save all file names as an array.

The code is as follows:

<?php
$s=explode("/n",trim(`dir/b e://video`));
print_r($s);
?>
<?php 
$dir="E:/video"; //这里输入其它路径 
//PHP遍历文件夹下所有文件 
$handle=opendir($dir."."); 
echo "文件:<br>"; 
while (false !== ($file = readdir($handle))) 
{ 
if ($file != "." && $file != "..") { 
$file=$file.&#39;,&#39;; //输出文件名 
$file=explode(&#39;,&#39;,$file);
} 
} 
print_r($file);//输出的就是数组了
closedir($handle); 
?>
<?php 
$dir="."; //这里输入其它路径 
//PHP遍历文件夹下所有文件 
$handle=opendir($dir."."); 
echo "文件:<br>"; 
//定义用于存储文件名的数组
$array_file = array();
while (false !== ($file = readdir($handle))) 
{ 
if ($file != "." && $file != "..") { 
$array_file[] = $file; //输出文件名 
} 
} 
closedir($handle);
print_r("<pre class="brush:php;toolbar:false">");
print_r($array_file);
print_r("
"); ?>


The above is the detailed content of Introducing several methods of traversing directories and folders in PHP. For more information, please follow other related articles on the PHP Chinese website!

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