没有设置cookie Symfony 3

问题描述 投票:-1回答:2

我想弄清楚在Symfony 3中设置cookie的正确方法是什么。在这里阅读帖子后,我发现它会像这样工作;

$response = new Response();
$cookie = new Cookie("source", "$testing", time()+86400);
$response->headers->setCookie($cookie);

响应和Cookie都是HttpFoundation组件。但是,在基本控制器中设置后;

/**
* @Route("/", name="homepage")
*/
    public function indexAction(Request $request)
    {
        $response = new Response();
        $cookie = new Cookie("source", "testing", time()+86400);
        $response->headers->setCookie($cookie);

        return $this->render('index.html.twig');
    }

访问该页面后根本没有设置cookie;

Cookie not being set

我在这里做错了吗?

评论中有人要求提供$ response的var_dump;

object(Symfony\Component\HttpFoundation\Response)#370 (6) {
  ["headers"]=> object(Symfony\Component\HttpFoundation\ResponseHeaderBag)#371 (5) {
    ["computedCacheControl":protected]=> array(2) {
      ["no-cache"]=> bool(true)
      ["private"]=> bool(true)
    }
    ["cookies":protected]=> array(1) {
      [""]=> array(1) {
        ["/"]=> array(1) {
          ["source"]=> object(Symfony\Component\HttpFoundation\Cookie)#372 (9) { 
            ["name":protected]=> string(6) "source"
            ["value":protected]=> string(7) "testing"
            ["domain":protected]=> NULL
            ["expire":protected]=> int(1495910350)
            ["path":protected]=> string(1) "/"
            ["secure":protected]=> bool(false)
            ["httpOnly":protected]=> bool(true)
            ["raw":"Symfony\Component\HttpFoundation\Cookie":private]=> bool(false)
            ["sameSite":"Symfony\Component\HttpFoundation\Cookie":private]=> NULL
          }
        }
      }
    }
    ["headerNames":protected]=> array(2) {
      ["cache-control"]=> string(13) "Cache-Control"
      ["date"]=> string(4) "Date"
    }
    ["headers":protected]=> array(2) {
      ["cache-control"]=> array(1) {
        [0]=> string(17) "no-cache, private"
      }
      ["date"]=> array(1) {
        [0]=> string(29) "Fri, 26 May 2017 18:39:10 GMT"
      }
    }
    ["cacheControl":protected]=> array(0) { }
  }
  ["content":protected]=> string(0) ""
  ["version":protected]=> string(3) "1.0"
  ["statusCode":protected]=> int(200)
  ["statusText":protected]=> string(2) "OK"
  ["charset":protected]=> NULL
}
php symfony cookies
2个回答
1
投票

我想我已经明白了。返回期望响应,并且render函数提供完整响应。为了放入一个cookie,我需要在返回函数之前将它添加到render生成的响应中,如下所示;

$response = $this->render('index.html.twig');
$cookie = new Cookie("source", "testing", time()+86400);
$response->headers->setCookie($cookie);

return $response;

0
投票

您忘记发送您创建的回复。只需添加$ response-> send();设置cookie后。

    /**
    * @Route("/", name="homepage")
    */
    public function indexAction(Request $request)
    {
        $response = new Response();
        $cookie = new Cookie("source", "testing", time()+86400);
        $response->headers->setCookie($cookie);
        $response->send();

        return $this->render('index.html.twig');
    }
© www.soinside.com 2019 - 2024. All rights reserved.