How do I do HTTP basic authentication with Guzzle?

To do HTTP basic authentication with Guzzle, pass an auth array containing the username and password. You can set it once on the Client so it applies to every request, or pass it per request when only some calls need it.

Setting auth on the client

Pass auth in the Client constructor to authenticate every request made with that client:

use GuzzleHttp\Client;

$client = new Client([
    'auth' => ['user', 'passwd']
]);

$response = $client->get('https://httpbingo.org/basic-auth/user/passwd');
$body = $response->getBody();
echo $response->getStatusCode() . PHP_EOL;
echo $body;

Here's what the output will look like:

Terminal output of the client-level Guzzle basic auth script showing status 200 and authenticated true

Setting auth per request

Pass auth as a request option instead if only specific requests need credentials:

use GuzzleHttp\Client;

$client = new Client();
$response = $client->get('https://httpbingo.org/basic-auth/user/passwd', [
    'auth' => [
        'user',
        'passwd'
    ]
]);
$body = $response->getBody();
echo $response->getStatusCode() . PHP_EOL;
echo $body;

Here's what you will receive:

Terminal output of the per-request Guzzle basic auth script showing status 200 and authenticated true

If you're setting auth per request and want the session to persist across multiple requests without repeating credentials, tell Guzzle to persist cookies by passing 'cookies' => true when creating the Client.

Common errors and limitations

  • Unhandled 401 responses: without a try/catch around RequestException (or its ClientException subclass), a failed authentication attempt throws and stops script execution instead of letting you inspect the response.
  • Credentials in plain arrays: the auth array is sent as plain HTTP basic auth, which is base64-encoded, not encrypted. Only use it over HTTPS.

Related Guzzle web scraping questions: