Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Cookie variable in a Controller - Symfony2

I'm trying to set a cookie in a Controller before rendering a twig file. After trying out a few suggestions i saw here, my code looks like below:

public function demandAction() {

    $result = array('message' => '');
    $response = $this->render('MainBundle:Default:demand.html.twig', $result);        
    $response->headers->setCookie(new Cookie('cookie', 'value', time() + 3600 * 24 * 7));

    return $response;
}

But the cookie is not available in my rendered page when i alert document.cookie. I'm sure i must have missed something. Please help me out. Thanks.

like image 841
jcubav Avatar asked Aug 24 '26 08:08

jcubav


1 Answers

The cookie object has httpOnly set to true by default, http://api.symfony.com/2.0/Symfony/Component/HttpFoundation/Cookie.html

This means that the browser should not make the cookie visible to client-side scripts. If you need to see the cookie in your scripts you can pass the 7th parameter as false when you create the cookie.

$response->headers->setCookie(new Cookie('foo', 'bar',time() + 60, '/', null, false, false));

If you just need to view the cookie for debugging purposes you can use Chrome Dev tools. They are available under the 'Resources' tab.

like image 128
Rob K Avatar answered Aug 27 '26 00:08

Rob K