Eric David Sartor Eric David Sartor - 1 month ago 9
PHP Question

PHP recursive function causing PHP to run out of memory?

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.

Answer

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...
}
Comments