How to use proxy with authentication with Guzzle?

You can use an authenticated proxy with Guzzle very easily. You just need to pass in a proxy option when either creating a new Client object or when making the actual request. If the proxy uses authentication, just include the authentication options as part of the proxy string.

Here is what a proxy string with authentication parameters will look like:

http://username:password@proxyendpoint.com:port

Make sure to replace the username, password, proxyendpoint.com, and port with the required values based on the proxy you are using.

Here is some sample code that demonstrates how to use http and https proxies and also lists the endpoints that should not be connected via a proxy:

use GuzzleHttp\Client;

$client = new Client([
    "proxy" => [
        'http' => 'http://username:password@proxyendpoint.com:8886',
        'https' => 'http://username:password@proxyendpoint.com:8886',
				// Don't use a proxy with these
				'no' => ['yasoob.me', 'scrapingbee.com']    
    ],
    'verify' => false
]);

$response = $client->get('https://api.ipify.org/?format=json');

echo $response->getBody();

Sometimes proxy servers do not play well with SSL verification. Therefore, we included the verify => false option as well to disable SSL verification.

Note: Guzzle also respects the following environment variables for proxies: HTTP_PROXY, HTTPS_PROXY, and NO_PROXY.

You can read more about proxies in the Guzzle docs.

Related Guzzle web scraping questions: