Connecting Tech Pros Worldwide Help | Site Map

recursively traversing directory using php

Newbie
 
Join Date: Oct 2008
Posts: 26
#1: Aug 25 '09
I am try to write a program which can recursively traverse all files and if it finds directory then it goes inside that sub directory and list all files of that subdirectory, again comes back to main directory to traverse rest of the files...

Problem i am facing is, its just going inside first sub directory it comes across and then comes back to main directory, and treats all other files as files (even if its a directory). i am not able to figure out what is going wrong??

here is the code:

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. //dir_list.php
  3. $default_dir = "./test2";
  4. function traverseDir($dir) {
  5.  
  6.     echo "traversing $dir <br>";
  7.     if(!($dp = opendir($dir))) die("Cannot open $dir.");
  8.  
  9.     while((false !== $file = readdir($dp))){
  10.         echo "$dir/$file <br>";
  11.        //$dir_temp= $dir.'/'.$file;
  12.        if(is_dir("$dir/$file") ){
  13.             if($file != '.' && $file !='..'){
  14.                echo "this is  $file <br>";
  15.                traverseDir("$dir/$file");
  16.                echo "verify $dir<br>";
  17.  
  18.                chdir($dir);
  19.             }
  20.       }
  21.       else{
  22.             echo "this is file $file<br>";
  23.       }
  24.     }
  25.     closedir($dp);
  26.  
  27. }
  28. traverseDir($default_dir);
  29.  
  30. ?>
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,642
#2: Aug 25 '09

re: recursively traversing directory using php


it’s line 9: !== takes precedence over = thus $file is not updated. do it like in the comments, put brackets around the assignment.
Reply

Tags
directory, traverse