10

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

让我们看一下代码:

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 尚未创建。

4

2 回答 2

18

代替:

$response->send();

尝试使用:

$response->sendHeaders();

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

于 2013-06-28T07:42:19.910 回答
17

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

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

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

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

于 2012-07-20T05:11:15.657 回答