TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   General (http://www.talkphp.com/general/)
-   -   Glob recursion not working right (http://www.talkphp.com/general/4971-glob-recursion-not-working-right.html)

benton 09-26-2009 12:46 PM

Glob recursion not working right
 
I need to be able to read through all directories in a given path and list all of the files. I'm using the following code and it works for the top level but not sub-directories. For example, if there is this structure
Code:

dirA
 dirB
  fileB
 fileA

If will enter into dirA and display fileA. It will also show that it is going into the sub-directory dirB but fileB is never listed. Would someone please point out what I'm missing or let me know if there is a better way to do this?

PHP Code:

function GetAllFiles(&$files$locn)
{
  
$dirs glob($locn '/*'GLOB_ONLYDIR);
   
  if(
is_array($dirs) && count($dirs) > 0)
  {
    foreach (
$dirs as $dir)
    {
      
$cwd getcwd();
      
chdir ($dir);      
      
      foreach (
glob("*") as $filename
      {
         if (
is_dir($filename))
         {
           echo 
'enter subdir '.$filename.'<br>';
           
GetAllFiles($files$dir '/'.$filename);
         }  
               
         echo 
'file '.$filename .'<br>';
         
$files[] = $filename;
      }
       
chdir ($cwd); 
    }
  }



Salathe 09-26-2009 01:18 PM

It seems a bit of a convoluted method of traversing the directories, especially with changing the current working directory so often. You could change the call to the second glob (in the foreach) to use full (or relative) paths rather than just *. Or you could use the handy RecursiveDirectoryIterator which makes life easier.

benton 09-26-2009 03:06 PM

I'm not sure I understand how to make that change but I tried the following. The result is the same though. The sub-directories are listed but not their contents. This is actually the code I started with but when it didn't work, I added the recursive call to try to get in to the sub-directory.

As for RecursiveDirectoryIterator, I used that first and it did work in some cases. But besides it requiring php 5, the main problem is that it was causing an out of memory condition. That may have been due to the part of the code not shown where the contents of the files are read, but I decided to make it php 4 compatible and switched to the glob function.
PHP Code:

function GetAllFiles(&$files$locn

  
$dirs glob($locn '/*'GLOB_ONLYDIR); 
    
  if(
is_array($dirs) && count($dirs) > 0
  { 
    foreach (
$dirs as $dir
    { 
      foreach (
glob($dir '/*') as $filename)  
      { 
         echo 
'file '.$filename .'<br>'
         
$files[] = $filename
      } 
    } 
  } 




All times are GMT. The time now is 02:53 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0