Symfony 2: Setting Cookies

Symfony 2 is great but it’s not well documented yet and there is no documentation about cookie handling as well.

After a few code digging I’ve found the solution. As we know, basically, cookies are just HTTP headers and you can get them from requests or send with responses.

SymfonyComponentHttpFoundationResponse class has a public property named headers and its type is ResponseHeaderBag and ResponseHeaderBag has a method named setCookie. Voilà!

Now we can set cookies like this:

//in controller

$response = new Response();

$response->headers->setCookie(new Cookie(‘cookie_name’, ‘cookie_value’));

return $this->render(‘template_path’, array(..template_parameters…), $response);


As you can see setCookie method needs a Cookie object as parameter and it’s located in SymfonyComponentHttpFoundation. You can create a cookie object like this:

new Cookie($name, $value = null, $expire = 0, $path = ‘/’, $domain = null, $secure = false, $httpOnly = true);

That’s it!


2 thoughts on “Symfony 2: Setting Cookies

  1. Thanks a lot! This solved my cookie saving issue. This might be helpful to others as well.

    $request = $this->get(‘request’);
    $cookies = $request->cookies;

    Works to get the cookies

    if ($cookies->has(‘value))
    //do something

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s