我想从列表中搜索一些关于某个单词的链接。所以我正在制作一个脚本:
//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 "<br>";
}
else {
echo ($item."---Word Found!");
echo "<br>";
}
}
}
?>
Run Code Online (Sandbox Code Playgroud)
它工作正常。但有时脚本会突然停止工作。我不知道为什么。可能它进入一个没有响应的站点。但为此我使用了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);
Run Code Online (Sandbox Code Playgroud)
如果对于给定的超时下载速率低于给定的阈值,这将防止 curl 在慢速或死连接上“挂起”。达到超时后,您可以重试或跳过网址:
// skips the url if errors on download
$buffer = curl_exec($ch);
if ($buffer === FALSE) {
echo curl_error($ch);
continue;
}
Run Code Online (Sandbox Code Playgroud)
“停止工作”可能有多种原因。最简单的是,远程服务器在响应期间崩溃,而没有发送 TCP FIN。(我在野外见过这个)。因此,底层 TCP 连接不会关闭,并且 curl 会永远等待剩余的字节。
此外,在建立连接后在传输过程中阻止端口的防火墙规则也可能是原因。不太可能,但在野外也能看到。
我可以想象的另一个原因是,远程服务器计算了错误的“内容长度”HTTP 标头。与 HTTP/1.1 的 'Connection: keep-alive' 一起,这可能会使 curl 在等待永远不会发送的剩余字节时“挂起”。为了防止这种情况,您应该明确使用标题“连接:关闭”。这可以按如下方式完成:
curl_setopt(CURLOPT_HTTPHEADER, array('Connection: close'));
Run Code Online (Sandbox Code Playgroud)
但是,我的建议只是防止脚本挂起的解决方法。如果您想了解curl 挂起的原因,则必须跟踪网络流量。您可以使用 Wireshark。
| 归档时间: |
|
| 查看次数: |
2154 次 |
| 最近记录: |