Home > Article > Backend Development > PHP traverses and prints all file instances in the specified directory_PHP tutorial
function scan_dir($dir_name,$dir_flag=1) {
static $FILE_COUNT=1; //The initial value of the number of recorded files is 1 and the directory name is not remembered
$FILE_COUNT--; //Called once The scan_dir() function decrements itself by 1
@$dir_handle=opendir($dir_name); //Suppress error message display to facilitate custom error display
if(!$dir_handle)
die("Directory opening error! ");
while(false!==($filename=readdir($dir_handle))) //When the file name is '0', readdir returns FALSE to determine whether the return value is not equal
{
$flag=$dir_flag; // Weird is_dir($filename)! The path $filename must be found! Returns false when $filename does not exist or is not a directory
if($filename!='.'&&$filename!='..')
{
$FILE_COUNT++; Previous level path
while($flag>0&&--$flag) //Negative number is still true
echo ' ';
if(is_dir($dir_name.$filename)) //Determine whether it is A directory
{
echo ''."".$filename."
";
scan_dir($dir_name.$filename.'/',$dir_flag+1); //$dir_flag marks the directory tree level
}
else
{
echo "".$filename."
";
}
}
}
closedir($dir_handle); //Close the directory handle
echo "Total number of files:".$FILE_COUNT.'
';
}
scan_dir('D:wampwwwtestlamp61'); //Specified file path
?>