1
Fatal error: Allowed memory size of 805306368 bytes exhausted (tried to
allocate 8192 bytes) in *directory* on line 6

This is the error that's getting thrown when I try and access the page running this script:

$root = '../public_html/';

function proccess($dir) {
    $items = scandir($dir);
    $result = array();
    foreach ($items as $item)
    {
        if (is_dir($item))
            $result[$item] = proccess($item);
        else
            array_push($result, $item);
    }
    return $result;
}

print_r(proccess($root));

What I'm trying to accomplish is to build an associative array representing the directory tree in my public_html directory on my server. I'm trying to create a graphical index for myself...mainly just for fun, but this has turned into a learning experience about recursion!

To my eye, this function looks fairly straightforward and I don't have that many files on my server...so unless I've accidentally created an infinite recursion loop, I don't understand why I'm running out of memory.

The loop logic: scan the root directory, then loop through the resulting array. If it finds another directory, set it's name as the key for the $result array and run proccess() again. If it finds a file, simply push the filename to the $result array.

Eric David Sartor
  • 597
  • 2
  • 8
  • 22
  • see this http://stackoverflow.com/questions/952263/deep-recursive-array-of-directory-structure-in-php – sumit Nov 02 '16 at 03:44
  • By my eye, though I'm using different functions, isn't that function doing the EXACT same thing as mine, but using the DirectoryIterator object? I just tried it, and it worked actually...I don't understand why though...it looks identical to mine other than the fact that it's using DirectoryIterator... – Eric David Sartor Nov 02 '16 at 03:52

1 Answers1

6

The problem is scandir also returns . and .., which mean "this directory" and "the parent directory", respectively. SSo you're scanning the same directory infinitely. Just filter those out..

foreach ($items as $item){
     if($item=="." || $item == "..") continue;
     // rest of the code here...
}
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
  • 1
    Wow, yep, that was exactly it. The most frustrating thing is that I knew to filter those out, but because I didn't write this function, I forgot to add it back in. You're the real MVP. – Eric David Sartor Nov 02 '16 at 03:58