You can easily do HTTP basic authentication with
Guzzle
by passing in an auth
array with the username and password as part of the options while creating the Client
object. Guzzle will make sure to use these authentication credentials with all the follow-up requests made by the $client
.
Here is some sample code that uses an authentication endpoint at HTTP Bin to demonstrate this:
use GuzzleHttp\Client;
$client = new Client([
'auth' => ['user', 'passwd']
]);
$response = $client->get('https://httpbin.org/basic-auth/user/passwd');
$body = $response->getBody();
echo $response->getStatusCode() . PHP_EOL;
echo $body;
// Output:
// 200
// {
// "authenticated": true,
// "user": "user"
// }
Alternatively, you can specify the auth
credentials on a per-request basis as well:
$client = new GuzzleHttp\Client();
$response = $client->get('https://httpbin.org/basic-auth/user/passwd', [
'auth' => [
'user',
'passwd'
]
]);
$body = $response->getBody();
echo $response->getStatusCode() . PHP_EOL;
echo $body;
// Output:
// 200
// {
// "authenticated": true,
// "user": "user"
// }
Note: If you decide to use the latter method, you can
tell Guzzle to persist cookies
and use them for future requests by passing the 'cookies' => true
option while creating the Client
object.