ユーザーのセッションIDをCookieに保存したいと思います。
So I write this piece of code :
public function indexAction()
{
$session_id = $this->get('session')->getId();
$request = $this->get('request');
$value = $request->cookies->get('session_id');
if ($value == null)//if cookie session_id does not exist, we create it
{
$cookie = new Cookie('session_id', $session_id, time() + (3600 * 24 * 7));
$response = new Response();
$response->headers->setCookie($cookie);
$response->send();
}
else echo 'A cookie session_id has already been set :' . $value;
return $this->render('MyBundle:Default:index.html.twig');
}
1. First, I don't know where to put this code. I don't think putting it in the indexAction is the right thing.
2. A cookie PHPSESSID storing the session id already exists. Would it be better to change the expiry time of it rather than creating a new one ? How to change its expiry time then ?
3. To change the expiry time of my cookie session_id I tried :
$cookie = new Cookie('session_id', $session_id, time() + (3600 * 24 * 7));
- And setting in config.yml, below session,lifetime to 604800.
4.When I reopen the browser I also get the following error : Failed to start the session because headers have already been sent.
It seems thats is due to this call $this->get('session')
and also this line: $response->send();
but I don't how could I do it in another way.
But that does not work : when I close my browser and I reopen it all my cookies that I defined have gone, and PHPSESSID has a new value.