To send cookies with a Guzzle HTTP request in PHP, you need to create a CookieJar and attach it to the Guzzle Client instance. Here's an example code snippet to achieve this:
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
// Create a CookieJar instance
$cookieJar = new CookieJar();
// Add any required cookies to the CookieJar
$cookieJar->setCookie(new \GuzzleHttp\Cookie\SetCookie([
'Name' => 'cookie_name',
'Value' => 'cookie_value',
'Domain' => 'example.com',
'Path' => '/',
]));
// Create a Guzzle Client instance and attach the CookieJar
$client = new Client([
'base_uri' => 'https://example.com',
'cookies' => $cookieJar,
]);
// Send a request with the attached cookies
$response = $client->request('GET', '/api/endpoint');
// Process the response as needed
In this example, we create a CookieJar
object and add a cookie using the setCookie
method. The SetCookie
class is used to set cookie properties like name, value, domain, and path.
Then, we create a Guzzle Client
instance and pass the CookieJar
object to the cookies
option of the Client configuration. This attaches the cookies to all requests sent by the client.
Finally, we send a request using the client, and the attached cookies will be automatically sent along with the request. You can then process the response as needed.
Note: Make sure you have installed the Guzzle HTTP client library using Composer before using it in your PHP project. You can add the Guzzle dependency to your project by running the command: composer require guzzlehttp/guzzle
.