简体   繁体   English

CURLOPT_TIMEOUT,是否存在“其他”功能?

[英]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);      
    ?>

curl will close connection if can not connect within the 30 seconds. 如果在30秒钟内无法连接,curl将关闭连接。

as you can see, i'm using proxy list. 如您所见,我正在使用代理服务器列表。 however, some proxy ips sometimes have problems to connect within the 30 seconds, and curl is closing connection when can not load in 30 seconds. 但是,某些代理ip有时在30秒内无法连接,而curl在30秒内无法加载时会关闭连接。

i wanna try another ip for curl connect if curl timeout reached. 我想尝试另一个IP卷曲连接,如果达到卷曲超时。 right now, curl is closing everything if ip isn't working. 现在,如果ip不起作用,curl将关闭所有内容。 i wanna try another ip. 我想尝试另一个IP。 well, could you please suggest me a function? 好吧,能否请你建议我一个功能?

edited for @rubayeet. 为@rubayeet编辑。 added new proxy function 添加了新的代理功能

您只需要使用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

You have to create a new curl session to connect to another proxy. 您必须创建一个新的curl会话才能连接到另一个代理。 So put a foreach loop around your code and loop through your proxy array. 因此,在代码周围放置一个foreach循环并遍历代理数组。

Also you can use curl_errno() and curl_error() to check for an error (like your timeout). 您也可以使用curl_errno()和curl_error()来检查错误(例如超时)。

Maybe it would be useful to set CURLOPT_RETURNTRANSFER and load it into a var to modify or work on it. 设置CURLOPT_RETURNTRANSFER并将其加载到var中进行修改或处理可能会很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM