PHP is_file of and is_dir of are usage considerations when traversing a directory

  • 2020-03-31 20:24:41
  • OfStack

1. Catalog inc has the following contents:
Subdirectories 0
Subdirectories a.
Footer. HTML
The header. The HTML
Login_function. Inc., PHP
Mysqli_connect. PHP
Style. The CSS

2. Now PHP will traverse the inc directory and display only files, not directories 0 and a. The code is as follows:
 
$dir = $_SERVER['DOCUMENT_ROOT']; 
$dir = "$dir/inc/"; 
$d = opendir($dir); 
while(false !==($f=readdir($d))) 
{ 
if(is_file($f)){ 
echo " <h2>$f </h2>"; 
}else{ 
echo " <h2> Is a directory $f </h2>"; 
} 
} 
closedir($d); 

The result is that "footer.html" is a file and everything else is a directory:
Is a directory.
Is a directory..
Directory is a
Footer. HTML
Is directory header. HTML
Is a directory login_function. Inc., PHP
Is the directory mysqli_connect. PHP
Is directory style. CSS

This is because you can't use "$f" directly in is_file and is_dir. This will be assumed by PHP to be the file in the root directory, and I have the file footer.html in my root directory, so it will display correctly. Others do not. Change the code to:
To display correctly, you need to modify the code:
 
while(false !== ($f=readdir($d))) 
{ 
if(is_file("$dir/$f")){ 
echo "<h2>$f</h2>"; 
}else{ 
echo "<h2> Is a directory $f</h2>"; 
} 
} 
closedir($d); 

Related articles: