GuzzleHttp: how can I save a cookie from a POST response and use it in the next POST?

I use Guzzle to log into my API site, and the moment I log in with the correct credentials, I return a cookie with RefreshToken to send it the next call, here is my simple (and well working) code:

$client = new Client(array( 'cookies' => true )); $response = $client->request('POST', 'http://myapi.com/login', [ 'timeout' => 30, 'form_params' => [ 'email' => $request->get('email'), 'password' => $request->get('password'), ] ]); 

and I will return the correct answer with the cookie, I see the cookie with:

 $newCookies = $response->getHeader('set-cookie'); 

now, I need to use this cookie in future calls, and I know that Guzzle can save the cookie for me and send it automatically (or not) the next time I call it with "CookieJar" or "SessionCookieJar", I have tried to use it but I donโ€™t see the cookie in "jar", here is what I did:

 $cookieJar = new SessionCookieJar('SESSION_STORAGE', true); $client = new Client([ 'cookies' => $cookieJar ]); $response = $client->request .... 

but when I get the cookie from POST, I only see it with:

 $newCookies = $response->getHeader('set-cookie'); 

and itโ€™s not in the cookieJar, so it wonโ€™t send it on the next call. What am I missing here?

Thanks!

+8
source share
1 answer

According to the documentation provided here , ['cookies' => true] indicates the use of a common cookie for all requests, while ['cookies' => $jar] indicates the use of a specific cookie ( $jar ) for use with client requests / answers. So you will need to use either:

 $client = new Client(array( 'cookies' => true )); $response = $client->request('POST', 'http://myapi.com/login', [ 'timeout' => 30, 'form_params' => [ 'email' => $request->get('email'), 'password' => $request->get('password'), ] ]); // and using the same client $response = $client->request('GET', 'http://myapi.com/next-url'); // or elsewhere ... $client = new Client(array( 'cookies' => true )); $response = $client->request('GET', 'http://myapi.com/next-url'); 

or

 $jar = new CookieJar; $client = new Client(array( 'cookies' => $jar )); $response = $client->request('POST', 'http://myapi.com/login', [ 'timeout' => 30, 'form_params' => [ 'email' => $request->get('email'), 'password' => $request->get('password'), ] ]); // and using the same client $response = $client->request('GET', 'http://myapi.com/next-url'); // or elsewhere ... $client = new Client(array( 'cookies' => $jar // the same $jar as above )); $response = $client->request('GET', 'http://myapi.com/another-url'); 
+5
source

Source: https://habr.com/ru/post/1270379/


All Articles