Symfony2:设置cookie

Nad*_*ami 10 php cookies symfony

我正在尝试在登录控制器中设置一个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');
}
Run Code Online (Sandbox Code Playgroud)

我包括这些:

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;
Run Code Online (Sandbox Code Playgroud)

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

小智 18

代替:

$response->send();
Run Code Online (Sandbox Code Playgroud)

尝试使用:

$response->sendHeaders();
Run Code Online (Sandbox Code Playgroud)

在此之后你应该能够重定向.


Mun*_*Das 17

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

要在这样的浏览器集$httpOnly参数中公开cookie,请false:

new Cookie('user', $user, 0, '/', null, false, false); //last argument
Run Code Online (Sandbox Code Playgroud)

值得注意的是,在编辑时,框架被配置为默认情况下使用HttpOnly cookie:请参阅cookbook(cookie_httponly).