我试图找出在Symfony 3中设置cookie的正确方法。在这里阅读帖子后,我发现它会像这样工作;
$response = new Response();
$cookie = new Cookie("source", "$testing", time()+86400);
$response->headers->setCookie($cookie);
Response和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;
我在这里做错了吗?
评论中的某人要求提供$ 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
}
答案 0 :(得分:1)
我想我已经明白了。返回期望响应,并且render函数提供完整响应。为了放入一个cookie,我需要在返回函数之前将它添加到render生成的响应中,如下所示;
$response = $this->render('index.html.twig');
$cookie = new Cookie("source", "testing", time()+86400);
$response->headers->setCookie($cookie);
return $response;
答案 1 :(得分: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');
}