CURL停止工作



我想从一个列表中搜索一个单词的链接。所以我正在制作一个脚本:

//html code here.
<?
if (array_key_exists('form_action', $_POST)){
$pel=$_POST['url'];
$toplist=file_get_contents($pel);
$listgrabbing=explode("rn",$toplist);
foreach($listgrabbing as $item)
{    
$useragent="Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.1.4322; Alexa Toolbar; .NET CLR 2.0.50727)";
$urlto=$item;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $urlto);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_COOKIEJAR, "COOKIE.txt"); 
curl_setopt($ch, CURLOPT_COOKIEFILE, "COOKIE.txt"); 
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10); 
$buffer = curl_exec($ch);
$po = strpos($buffer,"article");
if ($po===false)
{
echo ($item."---Word didn't found!");
echo "<br>";
}
else {
echo ($item."---Word Found!");
echo "<br>";
}
}
}
?>

工作正常。但有时脚本突然停止工作。我不知道为什么。可能它会进入一个没有响应的网站。但是这里我用的是CURLOPT_CONNECTTIMEOUT。但是我还没有发现剧本有什么问题。

实际上我的问题是,脚本在运行时突然停止

尝试CURLOPT_LOW_SPEED_TIMECURLOPT_LOW_SPEED_LIMIT选项一起使用

// the download speed must be at least 1 byte per second
curl_setopt(CURLOPT_LOW_SPEED_LIMIT, 1);
// if the download speed is below 1 byte per second for
// more than 30 seconds curl will give up
curl_setopt(CURLOPT_LOW_SPEED_TIME, 30);

如果在给定的超时时间内下载速率低于给定的阈值,这将防止curl在缓慢或死连接上'挂起'。当达到超时时间时,您可以重试它或跳过url:

// skips the url if errors on download
$buffer = curl_exec($ch);
if ($buffer === FALSE) { 
    echo curl_error($ch);
    continue;
}

"停止工作"可能有几个原因。最简单的是,远程服务器在响应期间崩溃,没有发送aTCP FIN(我在野外见过这种情况)。这样底层的TCP连接就不会被关闭,curl会永远等待剩余的字节。

也可能是防火墙规则在连接建立后在传输过程中阻止端口的原因。不太可能,但在野外也见过。

我能想到的另一个原因是,远程服务器计算错误的"Content-Length"HTTP头。加上HTTP/1.1的"Connection: keep-alive",这可能会使curl在等待永远不会发送的剩余字节时"挂起"。为了防止这种情况,你应该显式地使用头'Connection: close'。可以这样做:

curl_setopt(CURLOPT_HTTPHEADER, array('Connection: close'));

然而,我的建议只是为了防止你的脚本挂起的变通办法。如果您想了解为什么 curl挂起,您必须跟踪网络流量。

最新更新