Symfony2 – Guzzle using cookies

Featured Image

rolve@sxc.hu

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.

//somecontroller.php

                 $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);

                 $client->getEventManager()->attach($plugin);

                 $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);
                    $req->setCookie($cookies);

                    $req->send();

//...

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

Cheers.

0
Top

Enjoyed this post?

Subscribe to our RSS Feed, Follow us on Twitter and spread it to your friends!

Author

Darko Goles

Mobile Team PHP Web developer

Darko is PHP – Web developer and web support, web services specialized team member of Inchoo's mobile team.

Other posts from this author

Discussion 0 Comments

Add Comment

Add Your Comment

Please wrap all source codes with [code][/code] tags.
Top