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.

2
  • see this stackoverflow.com/questions/952263/… Commented Nov 2, 2016 at 3: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... Commented Nov 2, 2016 at 3:52

1 Answer 1

7

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...
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.