Guzzle饼干处理

Pet*_*jci 5 php cookies rest session guzzle

我正在构建一个基于Guzzle的客户端应用程序.我陷入了cookie处理的困境.我正在尝试使用Cookie插件实现它,但我无法让它工作.我的客户端应用程序是标准的Web应用程序,只要我使用相同的guzzle对象,它看起来就像它一样,但是在请求中它不会发送正确的cookie.我FileCookieJar用来存储cookie.如何在多个guzzle对象中保留cookie?

// 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');
Run Code Online (Sandbox Code Playgroud)

xma*_*cos 5

您正在创建CookiePlugin第二个请求的新实例,您还必须在第二个(和后续)请求中使用第一个实例.

$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');
Run Code Online (Sandbox Code Playgroud)


小智 3

$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());
Run Code Online (Sandbox Code Playgroud)