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.

2 Answers 2

18

Instead of:

$response->send();

try to use:

$response->sendHeaders();

After this you should be able to redirect.

1
  • Thanks, it helped me too
    – Shaolin
    Dec 9, 2015 at 15:59
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).

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.