Search code examples
phpsymfonycookiesrequestresponse

Symfony2: Reading a Cookie with Request object not working


When I create a cookie $response object can read it perfectly, but when page is refreshed I get empty array. Searched for examples on google and found out that it must be done with request object, but it's not working at all. Do you have any ideas what I'm missing?

public function indexAction(Request $request) {

    $response = new Response();

    var_dump($response->headers->getCookies()); //GIVES EMPTY ARRAY
    var_dump($request->cookies->all()); //GIVES ONLY PHPSESSID, BUT NOT THE ONE CREATED
    var_dump($request->cookies->get('user')); //GIVES NULL

    // ... //

    if ($loginForm->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $dql = // ... //                    ));
        $result = $dql->getArrayResult();

        if ($result) {
            foreach ($result as $profile) {
                $cookie = // ... //
                $response->headers->setCookie(new Cookie('user', $cookie, $expire = 0, $path = '/', $domain = 'null', $secure = false, $httpOnly = false));
                $response->sendHeaders();
            }

            var_dump($response->headers->getCookies()); //GIVES CORRECT COOKIE OBJECT
            var_dump($request->cookies->all()); //GIVES ONLY PHPSESSID, BUT NOT THE ONE CREATED
            var_dump($request->cookies->get('user')); //GIVES NULL
        }

Solution

  • You're setting the domain to "null" (a string), so when you're trying to read it, it's not showing up because you're not under "null" domain. If you want to use the defaults it should be just null (not a string).