Guzzle cookies handling

£可爱£侵袭症+ 提交于 2019-11-30 05:47:49

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');
$cookiePlugin = new CookiePlugin(new FileCookieJar($cookie_file_name));

// Add the cookie plugin to a client
$client = new Client($domain);
$client->addSubscriber($cookiePlugin);

// Send the request with no cookies and parse the returned cookies
$client->get($domain)->send();

// Send the request again, noticing that cookies are being sent
$request = $client->get($domain);
$request->send();

print_r ($request->getCookies());

Current answers will work if all requests are done in the same user request. But it won't work if the user first log in, then navigate through the site and query again later the "Domain".

Here is my solution (with ArrayCookieJar()):

Login

$cookiePlugin = new CookiePlugin(new ArrayCookieJar());

//First Request
$client = new Client($domain);
$client->addSubscriber($cookiePlugin);
$request = $client->post('/login');
$response = $request->send();

// Retrieve the cookie to save it somehow
$cookiesArray = $cookiePlugin->getCookieJar()->all($domain);
$cookie = $cookiesArray[0]->toArray();

// Save in session or cache of your app.
// In example laravel:
Cache::put('cookie', $cookie, 30);

Other request

// Create a new client object
$client = new Client($domain);
// Get the previously stored cookie
// Here example for laravel
$cookie = Cache::get('cookie');
// Create the new CookiePlugin object
$cookie = new Cookie($cookie);
$cookieJar = new ArrayCookieJar();
$cookieJar->add($cookie);
$cookiePlugin = new CookiePlugin($cookieJar);
$client->addSubscriber($cookiePlugin);

// Then you can do other query with these cookie
$request = $client->get('/getData');
$response = $request->send();

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!