10

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.

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.

Nadjib Mami
  • 5,736
  • 9
  • 37
  • 49

2 Answers2

18

Instead of:

$response->send();

try to use:

$response->sendHeaders();

After this you should be able to redirect.

hotclubplay
  • 181
  • 1
  • 2
17

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.

To expose the cookie in such a browser set $httpOnly argument to 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 not use HttpOnly cookies by default: see the cookbook (cookie_httponly).

Lg102
  • 4,733
  • 3
  • 38
  • 61
Mun Mun Das
  • 14,992
  • 2
  • 44
  • 43