How to set cookies in Goutte?

6.7k views Asked by At

I can't figure out how to set cookies in Goutte. I am trying following code :

$client->setHeader('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36');
$client->getCookieJar()->set('SRCHUID');

I am attaching an image of cookie with this name. How can I set this cookie?

enter image description here

2

There are 2 answers

0
degee147 On

Goutte with Guzzle 6

use GuzzleHttp\Cookie;

$cookieJar = new \GuzzleHttp\Cookie\CookieJar(true);

$cookieJar->setCookie(new \GuzzleHttp\Cookie\SetCookie([
       'Domain'  => "www.domain.com",
       'Name'    => $name,
       'Value'   => $value,
       'Discard' => true
 ]));

 $client = new Client();
 $guzzleclient = new \GuzzleHttp\Client([
        'timeout' => 900,
        'verify' => false,
        'cookies' => $cookieJar
  ]);
  $client->setClient($guzzleclient);

  return $client; //or do your normal client request here e.g $client->request('GET', $url);
0
Ralf Michael On

For me using the GuzzleClient didn't work. I used the CookieJar returned by getCookieJar. The only mistake I see in the initial question is that you try to set a cookie by only providing a string value. The set method needs a Cookie Instance to work. The methods signature is:

/**
 * Sets a cookie.
 *
 * @param Cookie $cookie A Cookie instance
 */
public function set(Cookie $cookie)

Example:

$this->client->getCookieJar()->set(new Cookie($name, $value, null, null, $domain));

Take care to not encode the cookie value or set encodedValue true

signature of the Cookie __construct:

/**
 * Sets a cookie.
 *
 * @param string $name         The cookie name
 * @param string $value        The value of the cookie
 * @param string $expires      The time the cookie expires
 * @param string $path         The path on the server in which the cookie will be available on
 * @param string $domain       The domain that the cookie is available
 * @param bool   $secure       Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client
 * @param bool   $httponly     The cookie httponly flag
 * @param bool   $encodedValue Whether the value is encoded or not
 */
public function __construct($name, $value, $expires = null, $path = null, $domain = '', $secure = false, $httponly = true, $encodedValue = false)