Symfony2:设置cookie [英] Symfony2: setting a cookie
问题描述
我尝试在登录控制器中设置一个cookie来实现记住我系统。即使我使用我在网络上找到的确切代码,我的错误。我希望你能帮助我弄清楚我错过了什么。
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.
我们来看一下代码:
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');
}
我包括这些:
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;
请注意,登录工作正常,会话已创建,但cookie尚未创建。
Note that logging-in works fine, the session has been created, but the cookie hasn't.
推荐答案
默认情况下 Symfony \Component\HttpFoundation\Cookie 创建为 HttpOnly ,它会触发支持浏览器的安全措施;这有助于在javascript中减少某些XSS攻击。
By default Symfony\Component\HttpFoundation\Cookie is created as HttpOnly, which triggers security measures in supporting browsers; this helps mitigate certain XSS attacks possible in javascript.
在这样的浏览器集中暴露cookie $ httpOnly
false :
To expose the cookie in such a browser set $httpOnly
argument to false
:
new Cookie('user', $user, 0, '/', null, false, false); //last argument
值得注意的是,在编辑时,框架被配置为不是默认使用HttpOnly Cookie:请参阅食谱(cookie_httponly)。
It's worth noting that at the time of this edit the framework is configured to not use HttpOnly cookies by default: see the cookbook (cookie_httponly).
这篇关于Symfony2:设置cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!