blog and things oh hi there!
Passing cookies between requests in Guzzle

I recently had to write for two endpoint calls that shared a cookie to indicate that the request was authenticated and here is how I did it with guzzle.

Get guzzle via Composer :

{
    "require": {
        "guzzlehttp/guzzle": "^6.2"
    }
}

And here is an example of how you might use it between two requests.

require __DIR__.'/vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;

try {
    $guzzle = new Client();
    $cookieJar = new CookieJar();

    $response = $guzzle->post(
        'https://first.request', [
            'cookies' => $cookieJar,
        ]
    );

    $response = $guzzle->get(
        'https://next.request', [
            'cookies' => $cookieJar,
        ]
    );

} catch (Exception $e) {
    throw new Exception($e->getMessage());
}

As you can see, the only trick to it is to share the same cookie object between the two requests. That's it!

© 2019 Kevin Jung