Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: setting a cookie

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.

like image 426
Nadjib Mami Avatar asked Jul 19 '12 18:07

Nadjib Mami


People also ask

Are cookies set automatically?

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.

How do I set cookies to all path?

In your Java server, you should call cookie. setPath("/") before adding it to response. Such cookie will match all request URIs.

How do you check cookies is set or not?

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.


2 Answers

Instead of:

$response->send();

try to use:

$response->sendHeaders();

After this you should be able to redirect.

like image 70
hotclubplay Avatar answered Oct 05 '22 22:10

hotclubplay


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).

like image 42
Mun Mun Das Avatar answered Oct 06 '22 00:10

Mun Mun Das