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.
Cookies are usually set by a web-server using the response Set-Cookie HTTP-header. Then, the browser automatically adds them to (almost) every request to the same domain using the Cookie HTTP-header.
In your Java server, you should call cookie. setPath("/") before adding it to response. Such cookie will match all request URIs.
Right-click and click on Inspect Element to open the developer console. Go to the Storage tab. Expand the Cookies menu and select the website to check cookies. On the right side of the console, you will see the cookies that have been set on the website.
Instead of:
$response->send();
try to use:
$response->sendHeaders();
After this you should be able to redirect.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With