I'm having difficulties in managing Cookies in Symfony2.
All my data is manipulated in an Controller used as service for another Controller (I have tested outside this controller and I have the same issue).
I use the followings:
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Cookie;
To set a Cookie, I use Cookie() and Response()
public function indexAction()
{
$cookie = new Cookie('mycookie', 'myvalue' );
$response = new Response();
$response->headers->setCookie( $cookie );
$response->send();
return $this->render('MyBundle:Default:default.html.twig', array());
}
All is ok here, I can view the Cookie dumping a $_COOKIE var and I can see it using various browser plugins. But the problem is that I cannot read/get it.
I tried 2 methods, none of them were successful.
public function readAction()
{
// Method 1
$request = new Request;
$cookies = $request->cookies;
var_dump( $cookies->get('mycookie') );
// Method 2
$response = new Response();
$cookies = $response->headers->getCookies();
var_dump($cookies);
// Return My Response
}
Any ideas what am I doing wrong here? To be noticed that I am just starting using Symfony2.
You are creating new Request
& Response
object instead of using pre-initialized ones. Try in this way,
public function readAction(Request $request) // <-- Notice the change
{
// Method 1
$cookies = $request->cookies;
var_dump( $cookies->get('mycookie') );
// Method 2
$response = $this->getResponse(); // <-- Notice the change
$cookies = $response->headers->getCookies();
var_dump($cookies);
// Return My Response
}