recursively traversing directory using php

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rahullko05
    New Member
    • Oct 2008
    • 34

    recursively traversing directory using php

    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:

    Code:
    <?php
    //dir_list.php
    $default_dir = "./test2";
    function traverseDir($dir) {
    	
    	echo "traversing $dir <br>";
    	if(!($dp = opendir($dir))) die("Cannot open $dir.");
    	
    	while((false !== $file = readdir($dp))){
    		echo "$dir/$file <br>";
    	   //$dir_temp= $dir.'/'.$file;
    	   if(is_dir("$dir/$file") ){
    			if($file != '.' && $file !='..'){
    			   echo "this is  $file <br>";
    			   traverseDir("$dir/$file");
    			   echo "verify $dir<br>";
    			   
    			   chdir($dir);
    			}
    	  }
    	  else{
    			echo "this is file $file<br>";
    	  }
    	}
    	closedir($dp);
    
    }
    traverseDir($default_dir);
    
    ?>
    Last edited by Dormilich; Aug 25 '09, 01:46 PM. Reason: Please use [code] tags when posting code
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

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

    Comment

    Working...