【问题标题】:curl with a random proxy使用随机代理卷曲
【发布时间】:2016-12-10 23:13:14
【问题描述】:

我要疯了,想找出问题所在,但我找不到。

$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,然后在 cURL 请求中使用它。我得到的所有数据都是空白页。在某些情况下,我会获得无限的页面加载,但没有任何结果。是什么原因造成的,我该如何解决?谢谢。

【问题讨论】:

    标签: php curl proxy


    【解决方案1】:

    也许问题在于您的 loadProxies(5) 返回?因为这段代码现在在这里可以正常工作:

    <?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);
    

    另外,$data 只返回 curl 的返回码,而不是数据,因为默认情况下,curl 将响应正文输出到标准输出。如果您设置 CURLOPT_RETURNTRANSFER ,它将返回正文。 (要将其重定向到其他内容,请使用 CURLOPT_FILE )

    【讨论】:

    • $proxylist = loadProxies(2); var_dump($proxylist); 返回array(2) { [0]=&gt; string(34) "47.88.104.219:80" [1]=&gt; string(36) "14.161.21.170:8080" } 所以这是正确的。当我手动将它们键入 CURLOPT_PROXY 时,它可以工作,但当它是变量时则不行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 2018-12-18
    • 2011-01-31
    • 2017-03-05
    • 1970-01-01
    相关资源
    最近更新 更多