简体   繁体   中英

Lifetime of a cookie (for session id) ? Deleted after closing the browser + error : Failed to start the session because headers have already been sent

I would like to store in a cookie the session id of the user.

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.

You can set the session lifetime in your config file under the framework section. An example of config.yml could look like this:

framework:
secret:        %secret%
charset:       UTF-8
error_handler: null
csrf_protection:
  enabled: true
router:        { resource: "%kernel.root_dir%/config/routing.yml" }
validation:    { enabled: true, annotations: true }
templating:    { engines: ['twig'] } #assets_version: SomeVersionScheme
session:
  default_locale: %locale%
  lifetime:       3600
  auto_start:     true

You can find more information here: http://forum.symfony-project.org/viewtopic.php?f=23&t=34110

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM