Home  >  Article  >  Backend Development  >  Things to note about the is_file() and is_dir() functions when traversing directories

Things to note about the is_file() and is_dir() functions when traversing directories

WBOY
WBOYOriginal
2016-07-25 09:00:47924browse
  1. $dir = $_SERVER['DOCUMENT_ROOT'];
  2. $dir = "$dir/files/";
  3. $d = opendir($dir);
  4. while(false !== ($f=readdir($d)))
  5. {
  6. if(is_file($f)){
  7. echo "

    $f

    ";
  8. }else{
  9. echo "

    It is the directory $f

    ";
  10. }
  11. }
  12. closedir($d);
Copy the code

The result only shows that "footer.html" is a file, and the others have become directories: is a directory. It's a directory.. Is directory a footer.html Is the directory header.html Is the directory login_function.files.php Is the directory mysqli_connect.php It’s the directory style.css

The reason is that "$f" cannot be used directly in is_file and is_dir. This will be regarded by PHP as the file in the root directory, and there is the file footer.html in the root directory, so this file will be displayed correctly. Others don't. Just modify the code to the following content.

  1. while(false !== ($f=readdir($d)))
  2. {
  3. if(is_file("$dir/$f")){
  4. echo "< h2>$f";
  5. }else{
  6. echo "

    is the directory $f

    ";
  7. }
  8. }
  9. closedir($d);
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn