PHP using a custom function to traverse all files in the directory _php tips

Source: Internet
Author: User
Tags phpmyadmin

Directory traversal is a PHP design often used in a function, many PHP projects have this function module. Today in this article to illustrate the example of PHP using a custom function to traverse all the files in the directory method. The specific methods are as follows:

Method One: 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 ' is not a valid directory! '}
}
Listdir ('./phpmyadmin '); 

Method Two: Use Dir () to traverse the directory

This example uses the Dir () function traversal to return a directory class instance when the execution succeeds

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 article can give you some help in PHP program design.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.