Symfony2 – Guzzle using cookies

Featured Image ©

As seen in previous posts, Guzzle is easy to use php web client library. I explained how it can be used inside controller. But there is one problem more…
If you are using this for example to test log in with cookies based on PHPSESSID, you will get different PHPSESSID for client that runs inside controller then inside your browser from where you making Ajax call.

I investigated the way to handle this problem little bit and found workaround that works for me.
So in this article you will see how to use Guzzle with cookies and also some kind of workaround to make this cookies persistent so ‘test user’ log in will be persisted.

Inside Guzzle library you have also Cookie plug-in that will help us to handle cookie management in our code.

We will not using ArrayCookieJar but FileCookieJar to be able to make our cookies persistent, so when we fire up browser again and test same thing, cookie will be there where we saved it and we can continue using Guzzle web client with same session.

                 $client = new \Guzzle\Service\Client();
                 $filename = $this->get('kernel')->getCacheDir() . '/client_ses_' . $sess_id;
                 $cj = new \Guzzle\Http\CookieJar\FileCookieJar($filename);
                 $plugin = new CookiePlugin($cj);
                 $req = $client->post($url, $headers, $body);
                 $req->setOnComplete(function(\Guzzle\Http\Message\RequestInterface $req, \Guzzle\Http\Message\Response $resp, array $default) use($headers, &$ret, &$response) {
                                $resp_content = $resp->getBody();
                                $resp_headers = $resp->getRawHeaders();
//... do something with response
                    $req->getCurlOptions()->set(CURLOPT_SSL_VERIFYHOST, false);
                    $req->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false);

And that’s it. Now cookies are automatically handled and saved inside cache folder, and also automatically retreived next time we make request.


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.