php detailed multiple methods for traversing directories and folders

  • 2020-11-26 18:43:43
  • OfStack

Traversing the directory or traversing the directory under the specified type of file, which is every one of the children's shoes in writing the program will inevitably use. PHP itself also provides a number of functions that are often used, so when used correctly, you can't go wrong.
The following is a summary of my personal learning process, I hope to learn PHP children's shoes to help.
This function lists all files in the specified directory (including subdirectories)


function getfiles($path){ 
foreach(scandir($path) as $afile)
{
if($afile=='.'||$afile=='..') continue; 
if(is_dir($path.'/'.$afile)) 
{ 
getfiles($path.'/'.$afile); 
} else { 
echo $path.'/'.$afile.'<br />'; 
} 
} 
} // simple demo, Lists all files in the current directory 
getfiles(__DIR__);
 

scandir() returns an array of all the files and directories in the specified directory. In PHP, there is also a very powerful function called glob(). glob() takes two arguments, the second of which is optional and will be discussed later. Let's look directly at how glob() traverses the directory.
As you can see, the contents returned by glob() have been filtered out with '.' and '.. ', where * represents the traversal of all files in the directory. Accordingly, if you change to *.txt, all txt files in the directory will be traversed. Isn't it convenient? Its convenience can be more than this 1 point, according to Yuan Fang, it is also hidden inside a big secret, what is it? Say again later, if interested, can give me a message to exchange.

function getfiles($path){ 
foreach(glob($path) as $afile){ 
if(is_dir($afile)) 
{ getfiles($afile.'/*'); } else { echo $afile.'<br />'; } 
} 
} // simple demo, Lists all files in the current directory 
getfiles(__DIR__);0
 

If I say *.txt, it traverses all txt files in the directory, what if I want it to traverse several formats at the same time? How to do? There must be some children's shoes thought of using an array, and then quickly write out to replace in {*.txt,*.jpg,*.zip... }, of course, quickly found that the program returned false, nothing. Don't be disappointed, this refers to the second optional parameter mentioned earlier, which is used to change the behavior of glob. Please refer to the PHP manual for more details. } to match 'a', 'b' or 'c'... . Usage is as follows: foreach (glob ($path. '/ {*. txt, *. jpg, *. zip,... }', GLOB_BRACE) as $fileName){... }
For a complete walk through all of the specified file type functions in the directory, we can look at the following example

Iterate over all files in folders and subfolders


<html>
    <body>
        <?php
            function traverse($path = '.') {
                $current_dir = opendir($path);    //opendir() return 1 Three directory handles , Failure to return false
                while(($file = readdir($current_dir)) !== false) {    //readdir() Returns the open directory handle 1 An item 
                    $sub_dir = $path . DIRECTORY_SEPARATOR . $file;    // Build the subdirectory path 
                    if($file == '.' || $file == '..') {
                        continue;
                    } else if(is_dir($sub_dir)) {    // If it's a directory , recursively 
                        echo 'Directory ' . $file . ':<br>';
                        traverse($sub_dir);
                    } else {    // If it's a file , Direct output 
                        echo 'File in Directory ' . $path . ': ' . $file . '<br>';
                    }
                }
            }

            traverse('xxtt');
        ?>
    </body>
</html>

1 Some common examples

<?php
$dir="E:/video"; // I'm going to put in another path here 
//PHP Iterate over all the files under the folder 
$handle=opendir($dir."."); 
echo " file :<br>";
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..") {
echo $file; // Output file name 
}
}
closedir($handle); 
?>
 

Using this code to walk through all the files, help me save all the file names into an array.

<?php
$s=explode("/n",trim(`dir/b e://video`));
print_r($s);
?>
<?php 
$dir="E:/video"; // I'm going to put in another path here  
//PHP Iterate over all the files under the folder  
$handle=opendir($dir."."); 
echo " file :<br>"; 
while (false !== ($file = readdir($handle))) 
{ 
if ($file != "." && $file != "..") { 
$file=$file.','; // Output file name  
$file=explode(',',$file);
} 
} 
print_r($file);// The output is an array 
closedir($handle); 
?>
<?php 
$dir="."; // I'm going to put in another path here  
//PHP Iterate over all the files under the folder  
$handle=opendir($dir."."); 
echo " file :<br>"; 
// Defines an array to store file names 
$array_file = array();
while (false !== ($file = readdir($handle))) 
{ 
if ($file != "." && $file != "..") { 
$array_file[] = $file; // Output file name  
} 
} 
closedir($handle);
print_r("<pre>");
print_r($array_file);
print_r("</pre>");
?>


Related articles: