Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send Cookies with Guzzlehttp/guzzle 6?

I need to send a request with custom cookies.

I have tried to set cookieJar like this:

$cookieJar = CookieJar::fromArray(array($cookieName=>$cookieStr),                     'api.mobra.in');                  $res = $this->guzzleClient->request($requestMethod, $url,                     [                         'cookies' => [$cookieJar]                     ]                 ); 

But it is getting an error

cookies must be an instance of GuzzleHttp\Cookie\CookieJarInterface

Please suggest example or explain in details. I gone through documents but they have not mentioned in detail.

Thank you!

like image 356
steve Avatar asked Dec 06 '16 15:12

steve


People also ask

How do I set cookies in guzzle?

Guzzle can maintain a cookie session for you if instructed using the cookies request option. When sending a request, the cookies option must be set to an instance of GuzzleHttp\Cookie\CookieJarInterface .

What is the use of guzzle?

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. Simple interface for building query strings, POST requests, streaming large uploads, streaming large downloads, using HTTP cookies, uploading JSON data, etc...

How do I get my guzzle response code?

You can check to see if a request or response has a body using the getBody() method: $response = GuzzleHttp\get('http://httpbin.org/get'); if ($response->getBody()) { echo $response->getBody(); // JSON string: { ... } }


2 Answers

use GuzzleHttp\Cookie\CookieJar;  $cookieJar = CookieJar::fromArray([     'cookie_name' => 'cookie_value' ], 'example.com');  $client->request('GET', '/get', ['cookies' => $cookieJar]); 

You can read the documentation here.

like image 97
Federkun Avatar answered Oct 05 '22 22:10

Federkun


One more way to add a cookie to the request with Guzzle:

$url = 'https://www.example.com'; $request_options = [   'headers' => ['Cookie' => 'COOKIE_NAME=VALUE'] ]; $response = $this->httpClient->request('GET', $url, $request_options); 
like image 36
David Thomas Avatar answered Oct 05 '22 23:10

David Thomas