doumu6997 2016-11-02 03:41
浏览 214
已采纳

PHP递归函数导致PHP耗尽内存?

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.

  • 写回答

1条回答 默认 最新

  • dpl57372 2016-11-02 03:49
    关注

    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...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘