Set proxy in Guzzle Set proxy in Guzzle curl curl

Set proxy in Guzzle


As for Guzzle 6.

Guzzle docs give info about setting proxy for a single request

$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 Request HTTP error from a proxy. It is solved with another config structure (found in docs for guzzle 3)

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


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:password@192.168.16.1:10",]);

this worked with guzzle in php.


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

From Guzzle6 docs:

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