PHP traverses and prints all file instances in the specified directory

  • 2020-12-26 05:36:22
  • OfStack


<?php
// Function: Traverse and print all files in the specified directory 
function scan_dir($dir_name,$dir_flag=1) {
 static $FILE_COUNT=1;                // Number of records   Initial value for the 1  Directory name not remembered 
 $FILE_COUNT--;                       // Each call 1 time scan_dir() Function the decrement 1
 @$dir_handle=opendir($dir_name);     // Suppress error message display    Easy to customize error display 
 if(!$dir_handle)
 die(" Directory opening error! ");
 while(false!==($filename=readdir($dir_handle)))  // File name ' 0' When, readdir return  FALSE , to determine whether the return value is incomplete 
 {
  $flag=$dir_flag;                 // odd  is_dir($filename) ! $filename This path must be accessible! when $filename Returns if it does not exist or is not a directory false
  if($filename!='.'&&$filename!='..')
  {
   $FILE_COUNT++;                   // Do not record the current path and on 1 Class path 
   while($flag>0&&--$flag)          // Negative numbers are still true 
   echo '&nbsp;';
   if(is_dir($dir_name.$filename))  // judge   Whether it is 1 A directory 
   {
    echo '<strong>'."<a href=".$dir_name.$filename.">".$filename."</a></strong><br>";
    scan_dir($dir_name.$filename.'/',$dir_flag+1);      //$dir_flag Flags the directory tree hierarchy 
   }
   else
   {
    echo "<a href=".$dir_name.$filename.">".$filename."</a><br>";
   }
  }
 }
 closedir($dir_handle);                 // Close the directory handle 
 echo " The total number of files :".$FILE_COUNT.'<br>';
}
scan_dir('D:\wamp\www\test\lamp61');  // The specified file path 
?>


Related articles: