Search code examples
symfonycookiesguzzlesymfony-2.1zend-http-client

guzzle php http client cookies setup


I am trying to migrate from Zend Http Client to Guzzle Http Client. I find Guzzle well featured and easy to use for the most part, But I think it is not well documented when it comes to using Cookie plugin. So my question is how do you set cookies for the HTTP request you are going to make against the server, in Guzzle.

Using Zend Client you would do something as simple as :

$client = new HttpClient($url);   // Zend\Http\Client http client object instantiation
$cookies = $request->cookies->all();   // $request Symfony request object that gets all the cookies, as array name-value pairs, that are set on the end client (browser) 
$client->setCookies($cookies);  // we use the above client side cookies to set them on the HttpClient object and,
$client->send();   //finally make request to the server at $url that receives the cookie data

So, how do you do this in Guzzle. I have looked at http://guzzlephp.org/guide/plugins.html#cookie-session-plugin. But I felt it is not straightforward and couldn't get my head around it. May be someone can help ??


Solution

  • This code should achieve what is asked for, i.e to set the cookies on the request before making guzzle client request

    $cookieJar = new ArrayCookieJar();  // new jar instance
    $cookies = $request->cookies->all(); // get cookies from symfony symfony Request instance
    foreach($cookies as $name=>$value) {  //create cookie object and add to jar
      $cookieJar->add(new Cookie(array('name'=>$name, 'value'=>$value)));
    }
    
    $client = new HttpClient("http://yourhosturl");
    $cookiePlugin = new CookiePlugin($cookieJar);
    
    // Add the cookie plugin to the client object
    $client->addSubscriber($cookiePlugin);
    
    $gRequest = $client->get('/your/path');
    
    $gResponse = $gRequest->send();      // finally, send the client request
    

    When the response comes back from the server with set-cookie headers you have those cookies available in the $cookieJar.

    Cookie jar can also be gotten from the CookiePlugin method

    $cookiePlugin->getCookieJar();