The session cookie lifetime is to be updated on every request to your application.
A good place to do this is an event listener, I prefere to use subsribers instead of listeners so I will use a subscriber for this example, but a listener may be used too.
Since we want to send a cookie to the browser, we will listen to the kernel.response event.
<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class RequestSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
// return the subscribed events, their methods and priorities
return [
KernelEvents::RESPONSE => [
['refreshSessionCookie', 0],
],
];
}
public function refreshSessionCookie(ResponseEvent $event)
{
$session = $event->getRequest()->getSession();
if ($session->isStarted()) {
$response = $event->getResponse();
$lifetime = 3600;
$cookie = new Cookie($session->getName(), $session->getId(), time() + $lifetime);
$response->headers->setCookie($cookie);
}
}
}
You may also need to set the gc_maxlifetime
to make sure that the session file isn't deleted on the server side, and lost a user session even if the cookie is alive, in framework.yaml:
framework:
session:
gc_maxlifetime: 86400 # 1 day