2013-04-05 30 views
4

我正在构建基于Guzzle的客户端应用程序。我正在处理cookie处理。我试图使用Cookie plugin来实现它,但我无法实现它的工作。我的客户端应用程序是标准的Web应用程序,只要我使用相同的Guzzle对象,它看起来像是在工作,但是跨请求它不会发送正确的Cookie。我使用FileCookieJar来存储Cookie。我怎样才能让cookie跨多个吸引对象?Guzzle cookies handling

// 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'); 

回答

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()); 
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'); 
3

如果所有请求都是在同一个用户请求中完成的,那么当前的答案将起作用。但如果用户第一次登录,那么它将不起作用,然后浏览网站并在稍后再次查询“域”。

这里是我的解决方案(与ArrayCookieJar()):

登录

$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); 

其他要求

// 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();