我想从列表中搜索一些关于单词的链接.
所以我正在编写一个脚本:
//html code here.
if (array_key_exists('form_action', $_POST)){
$pel=$_POST['url'];
$toplist=file_get_contents($pel);
$listgrabbing=explode("\r\n",$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 "
";
}
else {
echo ($item."---Word Found!");
echo "
";
}
}
}
?>
它工作正常.但有时脚本会突然停止工作.我不知道为什么.
可能它会进入一个没有响应的网站.但为此我使用了CURLOPT_CONNECTTIMEOUT.但我还没有发现脚本中有什么问题.
其实我的问题是,脚本在运行时突然停止.
解决方法:
尝试使用CURLOPT_LOW_SPEED_TIME选项和CURLOPT_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);
如果对于给定的超时,下载速率低于给定阈值,这将防止卷曲在慢速或死连接上“挂起”.达到超时后,您可以重试或跳过网址:
// skips the url if errors on download
$buffer = curl_exec($ch);
if ($buffer === FALSE) {
echo curl_error($ch);
continue;
}
“停止工作”有几个原因.最简单的是,远程服务器在响应期间崩溃而不发送TCP FIN. (我在野外看过这个).因此,底层的TCP连接不会被关闭,curl会等待 – 永远 – 等待剩余的字节.
此外,在建立连接之后在传输期间阻止端口的防火墙规则可能是原因.不太可能,但也在野外看到.
我能想象的另一个原因是远程服务器计算错误的’Content-Length’HTTP头.与HTTP / 1.1的’Connection:keep-alive’一起,这可能会使curl’挂起’,同时等待永远不会发送的字节.为防止这种情况,您应该明确使用标题’Connection:close’.这可以按如下方式完成:
curl_setopt(CURLOPT_HTTPHEADER, array('Connection: close'));
但是我的建议只是防止脚本挂起的解决方法.如果你想了解curl挂起的原因,你必须追踪网络流量.你可以使用Wireshark.
标签:php,curl
来源: https://codeday.me/bug/20190629/1329749.html