Matt
Matt

Reputation: 2843

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

Upvotes: 18

Views: 46095

Answers (1)

AlterPHP
AlterPHP

Reputation: 12727

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'));
    }
}

Upvotes: 60

Related Questions