How PHP traverses the directory file

Source: Internet
Author: User
Tags glob
This article mainly introduces the PHP traversal directory files commonly used methods, combined with the example form summary of PHP for files and directories commonly used traversal skills and operating efficiency, has a certain reference value, the need for friends can refer to the next

Specific as follows:

Test algorithm (source code through the site tools format processing, for readers to read)

Algorithm 1. Short Line

foreach (Glob (' *. * ') as $filename) {  echo ' filename: '. $filename.;}

Algorithm 2. Rule of law

if ($handle = Opendir (' c:\\inetpub\\wwwroot\\test\\ ')) {  echo "files:\n";  while (false!== ($file = Readdir ($handle))) {    echo "$file \ n";  }  Closedir ($handle);}

Algorithm 3. Function system

function tree ($directory) {  $mydir =dir ($directory);  while ($file = $mydir->read ()) {    if ((Is_dir ("$directory/$file") and ($file! = ".") and ($file! = "..."))    {      echo "$file \ n";      Tree ("$directory/$file");    } else    echo "$file \ n";  }  echo "\ n";  $mydir->close ();} Tree ("c:\\inetpub\\wwwroot\\test\\");

Algorithm 4. Function System II

function Listdir ($dir) {  if (Is_dir ($dir)) {    if ($dh = Opendir ($dir)) {while      (($file = Readdir ($DH))!== false ) {        if (Is_dir ($dir. ") /". $file)) && $file! =". && $file! = "...") {          echo "filename:", $file;          Listdir ($dir. " /". $file." /");        } else{          if ($file! = "." && $file! = "...") {            echo $file;      }}} Closedir ($DH);}}  Listdir ("c:\\inetpub\\wwwroot\\test\\");

Algorithm 5. Recursive system

function File_list ($dir, $pattern = "") {  $arr =array ();  $dir _handle=opendir ($dir);  if ($dir _handle)  {while    ($file =readdir ($dir _handle)!==false)    {      if ($file = = = '. ' | | $file = = = '.. ')      {        continue;      }      $tmp =realpath ($dir. '/'. $file);      if (Is_dir ($tmp))      {        $retArr =file_list ($tmp, $pattern);        if (!emptyempty ($RETARR))        {          $arr []= $retArr;        }      } else      {        if ($pattern = = = "" "| | preg_ Match ($pattern, $tmp))        {          $arr []= $tmp;}}    }    Closedir ($dir _handle);  }  return $arr;} Print_r (File_list ("c:\\inetpub\\wwwroot\\test\\"));

Test method

We take the following content in the head and tail of the test code to detect the execution time and test 5 times to take the average result as the final result.

$stime =microtime (TRUE);//test Code//......//... $etime =microtime (true); $total = ($etime-$stime) *1000;echo "{$total} Millisecond (s) ";

Test results:

Algorithm 1

Algorithm 1 in the browser can correctly output all items, 5 times the time spent in the test is:

Average time = 3803.618621824 milliseconds

Algorithm 2

Algorithm 2 also outputs all items correctly in the browser, but at the beginning it gives ".." (parent directory) information. The time spent on 5 tests is:

Average time = 381.0853481294 milliseconds

Algorithm 3

Algorithm 3 in the browser can correctly output all items, also will still give ".." (parent directory) information. The time spent on 5 tests is:

Average time = 24299.2805485 milliseconds

Algorithm 4

The algorithm 4 and the algorithm 3 are similar, in the browser can correctly output all items, 5 times the time spent in the test is:

Average time = 24020.66812516 milliseconds

Algorithm 5

The algorithm 5 once made me think that IIS was out of the problem again. Although it can output all items correctly in the browser, the result of the data is set to the default array. The time spent on 5 tests is:

Average time = 61411.31243706 milliseconds

Test summary

Based on the test results, it is easy to draw the following speed rankings.

Algorithm 2 > Algorithm 1 > Algorithm 4 > Algorithm 3 > Algorithm 5

Why is algorithm 2 more efficient than other algorithms?

This is actually because the algorithm uses only the function "Readdir ()" That is built into PHP to read the contents of the directory. In addition to the algorithm 1, other algorithms in the reference Readdir (), in order to compensate for the deficiency of the function, a lot of other things done.

If you say, we need to specify all the files in the list of extensions. RT recommends using the pattern of algorithm 1, we will write the code so that we can.

foreach (Glob (' *. required extension ') as $filename) {  echo ' filename: '. $filename.;}


Whether as a novice or a senior programmer, in the code, the more attention should be paid to the efficiency and security of the program.

Please do not ignore any of the possibilities, and do not let the child-like code become the culprit that drags the server.

The above is the whole content of this article, I hope that everyone's study has helped.

Related Article

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: 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.