cURL 需要代理身份验证

2021-12-31 00:00:00 proxy curl php

我想使用 cURL 函数,但我在代理后面,所以我收到 HTTP/1.1 407 Proxy Authentication Required 错误...

I would like to use a cURL function, but I'm behind a proxy, so I get an HTTP/1.1 407 Proxy Authentication Required error...

这是我使用的php代码:

This is the php code I use:

$proxy_user = 'Michiel';
$proxy_pass = 'mypassword';
$proxy_url = 'myproxyurl:port';
$proxy = true;

$service_url = "https://www.myapiurltocall.com";
$service_user = 'user:password:FO';
$service_pass = 'password';

$ch = curl_init($service_url);

// Set proxy if necessary
if ($proxy) {
    curl_setopt($ch, CURLOPT_PROXY, $proxy_url);
    curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy_user.':'.$proxy_pass);
    curl_setopt($ch, CURLOPT_PROXYPORT, 8080);
    curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_NTLM);
}

// Set service authentication
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_USERPWD, "{$service_user}:{$service_pass}");

// HTTP headers
$headers['Authorization'] = 'Basic ' . base64_encode("$proxy_user:$proxy_pass");

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);    
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_TIMEOUT, 15);

//WARNING: this would prevent curl from detecting a 'man in the middle' attack
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);

$data = curl_exec($ch);

而且我不知道我做错了什么......我该如何解决这个错误?

And I don't know what I do wrong... How can I get around this error?

推荐答案

这是我最常用的:

function curlFile($url,$proxy_ip,$proxy_port,$loginpassw)
{
    //$loginpassw = 'username:password';
    //$proxy_ip = '192.168.1.1';
    //$proxy_port = '12345';
    //$url = 'http://www.domain.com';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_PROXYPORT, $proxy_port);
    curl_setopt($ch, CURLOPT_PROXYTYPE, 'HTTP');
    curl_setopt($ch, CURLOPT_PROXY, $proxy_ip);
    curl_setopt($ch, CURLOPT_PROXYUSERPWD, $loginpassw);
    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

相关文章