PHP uses custom function to realize traversing all files in directory

  • 2021-07-13 04:52:33
  • OfStack

Directory traversal is a function often used in PHP programming, and many PHP projects have this function module. Today, this article will give an example of PHP under parsing 1, which uses custom functions to traverse all files in the directory. The specific methods are as follows:

Method 1: Use readir () to traverse the directory

The implementation code is as follows:


function listDir($dir)
{
  if(is_dir($dir))
  {
    if($handle = opendir($dir))
    {
      while($file = readdir($handle))
      {
        if($file != '.' && $file != '..')
        {
          if(is_dir($dir.DIRECTORY_SEPARATOR.$file))
          {
            echo ' Directory name: '.$dir.DIRECTORY_SEPARATOR.'<font color="red">'.$file.'</font><br />';
            listDir($dir.DIRECTORY_SEPARATOR.$file);
          }else{
            echo ' Filename: '.$dir.DIRECTORY_SEPARATOR.$file.'<br />';
          }
        }
      }
    }
    closedir($handle);
  }else{
    echo ' Invalid directory !';
  }
}
listDir('./phpmyadmin'); 

Method 2: Use dir () to traverse the directory

In this example, the dir () function is used to traverse, and the Directory class instance is returned when the execution is successful


function tree($dir)
{
  $mydir = dir($dir);
  while($file = $mydir->read())
  {
    if($file != '.' && $file != '..')
    {
      if(is_dir("$dir/$file"))
      {
        echo ' Directory name: '.$dir.DIRECTORY_SEPARATOR.'<font color="red">'.$file.'</font><br />';
        tree("$dir/$file");
      }else{
        echo ' Filename: '.$dir.DIRECTORY_SEPARATOR.$file.'<br />';
      }
    }
  }
  $mydir->close();
}
tree('./phpmyadmin');

In addition, there are many ways to achieve directory traversal, I believe the method described in this paper can give everyone PHP programming to bring 1 help.


Related articles: