php 在 Guzzle 中设置代理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32324893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:54:39  来源:igfitidea点击:

Set proxy in Guzzle

phpcurlproxyguzzle

提问by mohammad shafiee

I have a problem with set proxy in guzzle that a blank page was shown while with curl everything works perfect. The code that I used in guzzle and curl came below. What is wrong with this code: Guzzle:

我在 guzzle 中设置代理时遇到问题,显示空白页面,而 curl 一切正常。我在 guzzle 和 curl 中使用的代码如下。这段代码有什么问题:Guzzle:

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

require_once "vendor/autoload.php";

try {
  $client = new Client();
  $request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
  $response = $client->send($request, [
      'timeout'  => 30,
      'curl'  => [
          'CURLOPT_PROXY' => '*.*.*.*',
          'CURLOPT_PROXYPORT' => *,
          'CURLOPT_PROXYUSERPWD' => '*:*',
      ],

  ]);
  echo '</pre>';
  echo($response->getBody());
  exit;
} catch (RequestException $e) {
  echo $e->getRequest();
  if ($e->hasResponse()) {
      echo $e->getResponse();
  }
}

And The code with CURL:

以及带有 CURL 的代码:

$url = 'http://httpbin.org';
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_PROXY, '*.*.*.*');
curl_setopt($ch, CURLOPT_PROXYPORT, *);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, '*:*');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$page = curl_exec($ch);
echo $page;

Thanks.

谢谢。

回答by shukshin.ivan

As for Guzzle 6.

至于狂饮6

Guzzle docsgive info about setting proxy for a single request

Guzzle 文档提供有关为单个请求设置代理的信息

$client->request('GET', '/', ['proxy' => 'tcp://localhost:8125']);

But you can set it to all requests when initializing client

但是你可以在初始化客户端时将其设置为所有请求

    $client = new Client([
        'base_uri' => 'http://doma.in/',
        'timeout' => 10.0,
        'cookie' => true,
        'proxy' => 'tcp://12.34.56.78:3128',
    ]);

UPD. I don't know why, but I face a strange behaviour. One server with guzzle version 6.2.2 works great with config as above, and the other one with the same version receives 400 Bad RequestHTTP error from a proxy. It is solved with another config structure (found in docs for guzzle 3)

更新。我不知道为什么,但我面临着一种奇怪的行为。一台 guzzle 版本 6.2.2 的服务器与上面的配置配合得很好,而另一台具有相同版本400 Bad Request的服务器从代理收到HTTP 错误。它是用另一个配置结构解决的(在guzzle 3 的文档中找到)

$client = new Client([
    'base_uri' => 'http://doma.in/',
    'timeout' => 10.0,
    'cookie' => true,
    'request.options' => [
        'proxy' => 'tcp://12.34.56.78:3128',
    ],
]);

回答by Golu

Had the same problem right now , and all i needed to do was use curl array keys as constants instead of strings ..

现在遇到了同样的问题,我需要做的就是使用 curl 数组键作为常量而不是字符串。

$response = $client->send($request, [
              'timeout'  => 30,
              'curl'  => [
                  CURLOPT_PROXY => '*.*.*.*',
                  CURLOPT_PROXYPORT => *,
                  CURLOPT_PROXYUSERPWD => '*:*',
             ],
         ]);

See CURL options Keys , they are not strings anymore.

请参阅 CURL 选项 Keys ,它们不再是字符串。

回答by Diego Santa Cruz Mendezú

for a proxy, if you have the username and password, you can use:

对于代理,如果您有用户名和密码,则可以使用:

$client = new GuzzleHttp\Client();

$res = $client->request("POST", "https://endpoint.com", [
    "proxy" => "http://username:[email protected]:10",
]);

this worked with guzzle in php.

这在 php 中与 guzzle 一起使用。

回答by ResRelentelss

For Guzzle6, I think the best way is to implement a middleware for setting proxy.

对于Guzzle6,我认为最好的方法是实现一个设置代理的中间件。

From Guzzle6 docs:

来自 Guzzle6 文档:

We can set proxy as below:

我们可以设置代理如下:

use Psr\Http\Message\RequestInterface;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Client;
use GuzzleHttp\Middleware;
use Util\Api;
function add_proxy_callback($proxy_callback) {
    return function (callable $handler) use ($proxy_callback) {
        return function (RequestInterface $request,$options) use ($handler,$proxy_callback) {
            $ip = $proxy_callback();
            $options['proxy'] = $ip;
            return $handler($request,$options);
        };
    };
} 
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(add_proxy_callback(function() {
    return Api::getIp(); //function return a ip 
}));
$client = new Client(['handler'=>$stack]);
$response = $client->request('GET','http://httpbin.org/ip');
var_dump((string)$response->getBody());

回答by Isuru Walpola

The procedure for psr-7 may be different, but if you're using the standard way to instantiate a client,

psr-7 的过程可能会有所不同,但如果您使用标准方式来实例化客户端,

path\to\project\vendor\guzzlehttp\guzzle\src\Client.php, lines 164-170includes code to read the environment variables to see if HTTP_PROXY and HTTPS_PROXY are set on the current machine, and if yes, Guzzle will use those values.

path\to\project\vendor\guzzlehttp\guzzle\src\Client.php,第 164-170 行包含读取环境变量的代码,以查看当前机器上是否设置了 HTTP_PROXY 和 HTTPS_PROXY,如果是,Guzzle 将使用这些值。

Additionally, I had to set my HTTPS_PROXY = http://ip:port(not https), because our workplace proxy seems to handle both https and http requests via the http protocol.

此外,我必须设置我的 HTTPS_PROXY = http://ip:port(不是 https),因为我们的工作场所代理似乎通过 http 协议处理 https 和 http 请求。

The advantage of this configuration is that you don't have to chnge proxy settings in your source code.

这种配置的优点是您不必在源代码中更改代理设置。

回答by Shaktik

$response = \Drupal::httpClient()->post($settings['base_url'] . 'api/search/', [
    'verify' => true,
    'body' => $post_data,
      'headers' => [
        'Content-type' => 'application/json',
      ],
    'curl' => [
        CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2, 
        CURLOPT_PROXY => 'proxyip:58080'],
    ]
  )->getBody()->getContents();

Set proxy/https in Guzzle and SSL its work perfect.

在 Guzzle 和 SSL 中设置代理/https 其工作完美。