[英]CURLOPT_TIMEOUT , is there “else” function?
<?php
function get_random_proxy()
{
srand ((double)microtime()*1000000);
$f_contents = file ("proxy.txt");
$line = $f_contents[array_rand ($f_contents)];
return $line;
}
$proxy = get_random_proxy();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "example.com");
curl_setopt($ch, CURLOPT_PROXY,$proxy);
curl_setopt($ch, CURLOPT_TIMEOUT ,30);
curl_exec($ch);
curl_close($ch);
?>
如果在30秒钟内无法连接,curl将关闭连接。
如您所见,我正在使用代理服务器列表。 但是,某些代理ip有时在30秒内无法连接,而curl在30秒内无法加载时会关闭连接。
我想尝试另一个IP卷曲连接,如果达到卷曲超时。 现在,如果ip不起作用,curl将关闭所有内容。 我想尝试另一个IP。 好吧,能否请你建议我一个功能?
为@rubayeet编辑。 添加了新的代理功能
您只需要使用curl_errno来测试是否发生了CURLE_OPERATION_TIMEDOUT
function get($url, $proxy){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PROXY,$proxy);
curl_setopt($ch, CURLOPT_TIMEOUT ,30);
$response = curl_exec($ch);
curl_close($ch);
return $response
}
$url = 'example.com';
while(true) {
$proxy = get_random_proxy();
$response = get($url, $proxy);
if ($response === False) continue;
else break;
}
//do something with $response
您必须创建一个新的curl会话才能连接到另一个代理。 因此,在代码周围放置一个foreach循环并遍历代理数组。
您也可以使用curl_errno()和curl_error()来检查错误(例如超时)。
设置CURLOPT_RETURNTRANSFER并将其加载到var中进行修改或处理可能会很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.