卷曲设置服务器地址代替代理

时间:2018-09-27 16:04:55

标签: php curl

很抱歉这个问题,但是我已经3天不知道错误在哪里了。我在自己的网站上有一个页面,其中显示了用户的IP地址,如下所示:

<?php
echo "<br>"."Your IP address :"."<br>";
echo @$_SERVER['HTTP_CLIENT_IP']."<br>";
echo @$_SERVER['HTTP_X_FORWARDED_FOR']."<br>";
echo @$_SERVER['REMOTE_ADDR']."<br>"
?>

并且当我仅通过curl发送一个请求时,此页面将完全按照我的意愿显示代理的地址:

$ch = curl_init("http://mysite/youIp.php");
$proxy = '180.210.205.107:3128';
curl_setopt($ch, CURLOPT_PROXY, $proxy); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curl_scraped_page = curl_exec($ch);
$result = curl_exec($ch);
echo $result;
curl_close($ch);

结果:

enter image description here

但是当我尝试通过curl函数使用多个请求时,所有操作都会失败:

$proxy = '180.210.205.107:3128';
function multirequest($urls)
{
    $multi = curl_multi_init();
    $handles = []; 
    $htmls = [];

    for($i=0; $i<count($urls);$i++)
    { 
        $url = $urls[$i]; 
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_PROXY, $proxy); 
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_multi_add_handle($multi, $ch);
        $handles[$url] = $ch; 
    }   

    do {  
        $mrc = curl_multi_exec($multi, $active);  
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);

    while ($active && $mrc == CURLM_OK) 
    {
        if (curl_multi_select($multi) == -1) 
        {
            usleep(1);
        }

        do
        {
            $mrc = curl_multi_exec($multi, $active);
        }while($mrc == CURLM_CALL_MULTI_PERFORM);
    }

    foreach($handles as $channel)
    {
        $html = curl_multi_getcontent($channel);
        $htmls[] = $html;
        curl_multi_remove_handle($multi, $channel);
    }

    curl_multi_close($multi);
    return $htmls;
}

运行来自数组的url请求(实际上,$urls仅包含1个url-到我自己的页面):

var_dump($urls);
// only 1 url -> http://mysite/youIp.php
foreach($urls as $url)
{
    $htmls = multirequest($url);
    foreach($htmls as $html)
    {
        echo $html;
    }
}

结果是,我看到了我的服务器IP地址:

enter image description here

我不知道为什么这段代码不起作用。如果您发现我在哪里弄错了,请提供帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

也许改变这个

$proxy = '180.210.205.107:3128';
function multirequest($urls)
{
    $multi = curl_multi_init();
    $handles = []; 
    $htmls = [];
    // ...

对此

function multirequest($urls)
{
    $proxy = '180.210.205.107:3128';
    $multi = curl_multi_init();
    $handles = []; 
    $htmls = [];
    // ...

换句话说,在函数内部定义$proxy