Guzzle cookies handling

Peter Krejci picture Peter Krejci · Apr 5, 2013 · Viewed 12.9k times · Source

I'm building a client app based on Guzzle. I'm getting stucked with cookie handling. I'm trying to implement it using Cookie plugin but I cannot get it to work. My client application is standard web application and it looks like it's working as long as I'm using the same guzzle object, but across requests it doesn't send the right cookies. I'm using FileCookieJar for storing cookies. How can I keep cookies across multiple guzzle objects?

// first request with login works fine
$cookiePlugin = new CookiePlugin(new FileCookieJar('/tmp/cookie-file'));
$client->addSubscriber($cookiePlugin);

$client->post('/login');

$client->get('/test/123.php?a=b');


// second request where I expect it working, but it's not...
$cookiePlugin = new CookiePlugin(new FileCookieJar('/tmp/cookie-file'));
$client->addSubscriber($cookiePlugin);

$client->get('/another-test/456');

Answer

xmarcos picture xmarcos · Sep 10, 2013

You are creating a new instance of the CookiePlugin on the second request, you have to use the first one on the second (and subsequent) request as well.

$cookiePlugin = new CookiePlugin(new FileCookieJar('/tmp/cookie-file'));

//First Request
$client = new Guzzle\Http\Client();
$client->addSubscriber($cookiePlugin);
$client->post('/login');
$client->get('/test/first');

//Second Request, same client
// No need for $cookiePlugin = new CookiePlugin(...
$client->get('/test/second');

//Third Request, new client, same cookies
$client2 = new Guzzle\Http\Client();
$client2->addSubscriber($cookiePlugin); //uses same instance
$client2->get('/test/third');