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

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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵