To authenticate with a remote server using Guzzle in PHP, you can use Basic Authentication. Here's an example:
composer require guzzlehttp/guzzle
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\RequestOptions;
$client = new Client();
$username = 'your_username';
$password = 'your_password';
try {
$response = $client->request('GET', 'https://example.com/api/endpoint', [
RequestOptions::AUTH => [$username, $password]
]);
$statusCode = $response->getStatusCode();
$content = $response->getBody()->getContents();
// Process the response data as necessary
// ...
} catch (GuzzleException $e) {
// Handle any errors
echo $e->getMessage();
}
In the example above, https://example.com/api/endpoint
is the URL of the remote server's API endpoint you want to access. The GET
method is used, but you can change it to POST
, PUT
, or others as required.
Additionally, $response->getStatusCode()
retrieves the HTTP status code of the response, and $response->getBody()->getContents()
gets the response content.
Remember to replace 'your_username'
and 'your_password'
with the actual credentials required for the remote server's authentication.
This is a basic example of how to authenticate with a remote server using Guzzle in PHP. You can refer to the Guzzle documentation for more advanced features and options.