How do I do HTTP basic authentication using Guzzle?



PHP Snippet 1:

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

PHP Snippet 2:

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

PHP Snippet 3:

$client = new Client([
    'auth' => ['username', 'password'],
]); 

PHP Snippet 4:

$client = new GuzzleHttp\Client();
$credentials = base64_encode('[email protected]:password');
$response = $client->get('http://www.server.com/endpoint', [
    'Authorization' => ['Basic '.$credentials]
]);

PHP Snippet 5:

$client = new Client();

$response = $client->request(
    'POST', /*instead of POST, you can use GET, PUT, DELETE, etc*/
    $url,
    [
      'auth' => ['username', 'password'] /*if you don't need to use a password, just leave it null*/
    ] 
);

echo $response->getBody();

PHP Snippet 6:

$response = $client->request( 'GET', 'your_url', [
                    'auth'    => [
                        'your_username',
                        'your_password'
                    ],
                    'headers' => [
                        'if you want to pass something in the headers'
                    ]
                ]
            );

PHP Snippet 7:

$client = new Client();
$credentials = base64_encode('username:password');
$response = $client->post('url',
        [
            'headers' => [
                'Authorization' => 'Basic ' . $credentials,
            ],
        ]);

PHP Snippet 8:

eight_points_guzzle:
    clients:         
        your_service:
            # Write here the host where to do requests
            base_url: "yourURL"

            options:
                timeout: 30
                auth:
                    - yourLogin     # login
                    - yourPassword # password
            plugin: ~

PHP Snippet 9:

$client  = $this->getContainer()->get('eight_points_guzzle.client.your_service');
$response = $client->get('yourRoute');

PHP Snippet 10:

 $client = new Client();
    $response = Http::withBasicAuth($username,$password)
    ->post($url);