Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 : Read Cookie

I've set a few cookies in a Controller action and then in another action I want to read the cookie set and do something with the value. However, when trying to read the cookies, all i see is an empty array, my code is as follows:

public function testSetCookieAction()
{
    $value = 'ABCDEFGHI'

    $cookie = new Cookie('SYMFONY2_TEST', $value, (time() + 3600 * 24 * 7), '/');
    $response = new Response();
    $response->headers->setCookie($cookie);
    $response->send();  
.
.
.
}

public function testReadCookieAction()
{
    $response = new Response();
$cookies = $response->headers->getCookies();

// $cookies = array(0) { } 
}

When i var_dump($_COOKIE);, I see array(1) { ["SYMFONY2_TEST"]=> string(9) "ABCDEFGHI" } Does anybody know what I am doing wrong?

Thanks in advance

like image 446
Matt Avatar asked Dec 08 '11 14:12

Matt


1 Answers

You must read cookies on the Request object, not on the void Response object you just created ;)

public function testReadCookieAction(Request $request)
{
    $cookies = $request->cookies;

    if ($cookies->has('SYMFONY2_TEST'))
    {
        var_dump($cookies->get('SYMFONY2_TEST'));
    }
}
like image 85
AlterPHP Avatar answered Nov 02 '22 19:11

AlterPHP