Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guzzle cookies handling

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');
like image 681
Peter Krejci Avatar asked Apr 05 '13 13:04

Peter Krejci


1 Answers

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');
like image 130
xmarcos Avatar answered Oct 03 '22 18:10

xmarcos