How do I do HTTP basic authentication using Guzzle?

Gopi K Mishra picture Gopi K Mishra · Jun 22, 2015 · Viewed 77.1k times · Source

I want to do basic access authentication using Guzzle and I am very new to programming. I have no clue what to do. I tried to do this using curl but my environment requires using guzzle.

Answer

ffflabs picture ffflabs · Jun 22, 2015

If you're using Guzzle 5.0 or newer, the docs say that basic auth is specified using the auth parameter:

$client = new GuzzleHttp\Client();
$response = $client->get('http://www.server.com/endpoint', [
    'auth' => [
        'username', 
        'password'
    ]
]);

Please note that the syntax is different if you're using Guzzle 3.0 or earlier. The constructor is different, and you also need to explicitly use the send method on a request to get a response:

$client = new Guzzle\Http\Client();
$request = $client->get('http://www.server.com/endpoint');
$request->setAuth('username', 'password');
$response = $request->send();