2016-08-04 87 views
0

我瘋了,試圖弄清楚是什麼問題,但我找不到它。用隨機代理捲曲

$proxies = loadProxies(5); 

function getData($proxylist) 
{ 
    $rand_proxy = rand(0,count($proxylist)-1); 
    $url = 'http://www.stackoverflow.com'; //just for example 
    $agent = "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/532.4 (KHTML, like Gecko) Chrome/4.0.233.0 Safari/532.4"; 
    $referer = "http://www.google.com/"; 

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_HEADER, 1); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    curl_setopt($ch, CURLOPT_USERAGENT, $agent); 
    curl_setopt($ch, CURLOPT_REFERER, $referer); 
    curl_setopt($ch, CURLOPT_PROXY, $proxylist[$rand_proxy]); 
    $data = curl_exec($ch); 
    curl_close($ch); 
    echo $data; 
} 

getData($proxies); 

應該取從陣列的隨機代理IP,然後在捲曲請求使用它。我得到的所有數據都是空白頁面。在某些情況下,我可以獲得無限的頁面加載量,並且不會有任何結果。是什麼導致了這個問題,我該如何解決這個問題?謝謝。

回答

0

也許問題是你的loadProxies(5)返回? CUS此代碼工作正常,就在這裏,現在:

<?php 
$proxies = array('86.188.142.244:8080'); // random public http proxy 

function getData($proxylist) 
{ 
    $rand_proxy = rand(0,count($proxylist)-1); 
    $url = 'http://www.stackoverflow.com'; //just for example 
    $agent = "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/532.4 (KHTML, like Gecko) Chrome/4.0.233.0 Safari/532.4"; 
    $referer = "http://www.google.com/"; 

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_HEADER, 1); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    curl_setopt($ch, CURLOPT_USERAGENT, $agent); 
    curl_setopt($ch, CURLOPT_REFERER, $referer); 
    curl_setopt($ch, CURLOPT_PROXY, $proxylist[$rand_proxy]); 
    $data = curl_exec($ch); 
    if($data!==true){$ex=new RuntimeException('curl_exec error. errno: '.curl_errno($ch).' error: '.curl_error($ch));@curl_close($ch);throw $ex;} 
    curl_close($ch); 
    //echo $data; 
} 

getData($proxies); 

也,$數據只是返回捲曲返回代碼,而不是數據,因爲在默認情況下,捲曲的響應體輸出到標準輸出。如果你設置了CURLOPT_RETURNTRANSFER,它會返回正文。 (將其重定向到其他地方,請使用CURLOPT_FILE)

+0

'$ proxylist = loadProxies(2); var_dump($ proxylist);'returns' array(2){[0] => string(34)「47.88.104.219:80」[1] => string(36)「14.161.21.170:8080」}'so那是對的。當我手動輸入_CURLOPT_PROXY_時,它可以工作,但不是當它是一個變量時。 – Nedas