php curl内存使用情况


php curl memory usage

我有一个函数,它从页面列表中获取html,并在两个小时左右,脚本中断并显示内存限制已被超过,现在我已经尝试取消设置/设置为null一些变量,希望能释放一些内存但问题是一样的。你们能看一下下面的一张吗代码?:

{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    if ($proxystatus == 'on'){
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
        curl_setopt($ch, CURLOPT_PROXY, $proxy);
    }
    curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
    curl_setopt($ch, CURLOPT_URL, $site);
    ob_start();
    return curl_exec($ch); // the line the script interrupts because of memory
    ob_end_clean();
    curl_close($ch);
    ob_flush();
    $site = null;
    $ch = null;
}

任何建议都将不胜感激。我已经将内存限制设置为128M,但之前增加它(对我来说似乎不是最好的选择)我想知道是否有在运行脚本时,我可以做任何事情来使用更少的内存/释放内存。

谢谢。

您确实在泄漏内存。请记住,return会立即结束当前函数的执行,因此永远不会调用所有清理(最重要的是ob_end_clean()curl_close())。

return应该是函数所做的最后一件事。

我知道这已经有一段时间了,但其他人可能会遇到类似的问题,所以如果它能帮助其他人。。。对我来说,这里的问题是curl被设置为将输出保存为字符串。[curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);就是这样]如果输出太长,脚本将耗尽该字符串所允许的内存。[返回类似FATAL ERROR: Allowed memory size of 134217728 bytes exhausted (tried to allocate 130027520 bytes)]的错误。解决方法是使用curl提供的其他输出方法之一:输出到标准输出,或输出到文件。无论哪种情况,都不需要ob启动。

因此,您可以将大括号的内容替换为以下任一选项:

选项1:输出到标准输出:

$ch = curl_init();
if ($proxystatus == 'on'){
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
    curl_setopt($ch, CURLOPT_PROXY, $proxy);
}
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch, CURLOPT_URL, $site);
curl_exec($ch);
curl_close($ch);

选项2:输出到文件:

$file = fopen("path_to_file", "w"); //place this outside the braces if you want to output the content of all iterations to the same file
$ch = curl_init();
if ($proxystatus == 'on'){
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
    curl_setopt($ch, CURLOPT_PROXY, $proxy);
}
curl_setopt($curl, CURLOPT_FILE, $file);    
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch, CURLOPT_URL, $site);
curl_exec($ch);
curl_close($ch);
fclose($file);  //place this outside of the braces if you want to output the content of all iterations to the same file

当然这不是cURL问题。使用xdebug之类的工具来检测脚本的哪个部分正在消耗内存。

顺便说一句,我也会把它改为两个小时不运行,我会把它移到每分钟运行一次的cronjob,检查它需要什么,然后停止。

相关文章: