2011-02-15 57 views
1
<?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將關閉連接。CURLOPT_TIMEOUT,是否有「其他」功能?

正如你所看到的,我使用代理列表。然而,一些代理服務器有時在30秒內連接有問題,而curl在30秒內無法加載時關閉連接。

我想嘗試另一個IP捲曲連接,如果捲曲超時達成。現在,如果ip不起作用,curl會關閉所有內容。我想嘗試另一個IP。那麼,請你給我建議一個功能?

編輯@rubayeet。添加新的代理功能

回答

1
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 
+0

多數民衆贊成我的代理功能。我如何使用它的功能?函數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(); – 2011-02-15 08:49:23

0

您必須創建一個新的curl會話才能連接到另一個代理。因此,在你的代碼周圍放一個foreach循環,並通過代理數組循環。

此外,您可以使用curl_errno()和curl_error()來檢查錯誤(如超時)。

也許設置CURLOPT_RETURNTRANSFER並將其加載到var中以修改或處理它會很有用。

+0

謝謝你的建議。我現在要嘗試他們......感謝功能.. – 2011-02-15 08:22:45

4

您只需要使用curl_errno來測試,如果發生CURLE_OPERATION_TIMEDOUT

+0

哦,是的。這就是我需要的。我從來沒有見過這個功能呢。感謝您的寶貴意見。 – 2011-02-15 08:24:21