PHP uses the glob method to traverse instances of all files under the folder

  • 2021-11-10 08:57:33
  • OfStack

Traversing all files under the folder, 1 can use opendir and readdir methods to traverse.


<?php
$path = dirname(__FILE__);
$result = traversing($path);
print_r($result);

function traversing($path){
 $result = array();
 if($handle = opendir($path)){
  while($file=readdir($handle)){
   if($file!='.' && $file!='..'){
    if(strtolower(substr($file, -4))=='.php'){
     array_push($result, $file);
    }
   }
  }
 }
 return $result;
}
?>

If you use the glob method to traverse, you can simplify the code


<?php
$path = dirname(__FILE__);
$result = glob($path.'/*.php');
print_r($result);
?>

Note that glob will return the path of path + search results, for example, path= '/home/fdipzone', as in the previous example.


Array
(
[0] => /home/fdipzone/a.php
[1] => /home/fdipzone/b.php
[2] => /home/fdipzone/c.php
)

This is different from the results returned by opendir and readdir.

If you just traverse the current directory. It can be changed to this: glob ('*. php');

Example: Use the glob method to traverse all php files under a specified folder (including subfolders).


Related articles: