Cookie basics for Symfony, Sensio Labs PHP framework

In Symfony, here is how you “get cookies”:

$response->headers->getCookies();

Don’t forget to include the class path:

use Symfony\Component\HttpFoundation\Cookie;

Setting cookie values in Symfony is pretty straight forward, the thing to know is that since Symfony processes so much in its front controllers you can set cookies deeper into your code than other methods where headers are sent much sooner. Since cookies can only be set before headers, this allows more flexibility within your design and coding and can also create problems like “where did that cookie go?!” unlike the olden days when you just assumed it was at the start of the new script!

$cookie = new Cookie('myCookie', 'cookieValue');
$response = new Response();
$response->headers->setCookie($cookie);

Accessing cookies directly in your TWIG template:
By the way, a separate templating engine for your views that has built-in log and ability to iterate values, etc is awesome, if you haven’t used TWIG, I highly recommend it!!!

{{ app.request.cookies.get('myCookie') }}

Here’s how to clear a cookie:

$response = new Symfony\Component\HttpFoundation\Response();
$response->headers->clearCookie('yourCookie');
$response->send();

In controller to update cookies, don’t forget to “SEND” the response.

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

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