php Symfony2:设置 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11567194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:47:02  来源:igfitidea点击:

Symfony2: setting a cookie

phpcookiessymfony

提问by Nadjib Mami

I'm trying to set a cookie within a login controller to achieve "remember me" system. Even though I've used the exact code I found on the web, things for me are going wrong. I hope you can help me figure out what I'm missing.

我正在尝试在登录控制器中设置 cookie 以实现“记住我”系统。尽管我使用了我在网上找到的确切代码,但对我来说还是出错了。我希望你能帮我弄清楚我错过了什么。

Let's go through the code:

让我们来看看代码:

public function loginAction(Request $request) {
// Receiving the login form
// Get Doctrine, Get EntityManager, Get Repository
if(/* form information matche database information */) {
     // Creating a session => it's OK
     // Creating the cookie
     $response = new Response();
     $response->headers->setCookie(new Cookie("user", $user));
     $response->send();
     $url = $this->generateUrl('home');
     return $this->redirect($url);

} else 
     return $this->render('***Bundle:Default:Login.html.php');
}

I included these:

我包括了这些:

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;

Note that logging-in works fine, the session has been created, but the cookie hasn't.

请注意,登录工作正常,会话已创建,但 cookie 尚未创建。

回答by hotclubplay

Instead of:

代替:

$response->send();

try to use:

尝试使用:

$response->sendHeaders();

After this you should be able to redirect.

在此之后,您应该能够重定向。

回答by Mun Mun Das

By default Symfony\Component\HttpFoundation\Cookieis created as HttpOnly, which triggers security measures in supporting browsers; this helps mitigate certain XSS attacks possible in javascript.

默认情况下,Symfony\Component\HttpFoundation\Cookie被创建为HttpOnly,这会触发支持浏览器的安全措施;这有助于缓解 JavaScript 中可能存在的某些 XSS 攻击。

To expose the cookie in such a browser set $httpOnlyargument to false:

要在这样的浏览器中公开 cookie,请将$httpOnly参数设置为false

new Cookie('user', $user, 0, '/', null, false, false); //last argument

It's worth noting that at the time of this edit the framework is configured to notuse HttpOnly cookies by default: see the cookbook (cookie_httponly).

值得注意的是,在进行此编辑时,框架被配置为默认使用 HttpOnly cookie:请参阅说明书 (cookie_httponly)