'Reset Symfony session lifetime/timeout on user activity
How do I reset the time of the Symfony session as long as there is activity of the user logged into the application.
in config.yml:
cookie_lifetime: 3600 # 1 hour
in parameters.yml
session_ttl: 3600
I want that after 50 minutes if the user performs an action in the application, the time of the session goes back to 1 hour.
Does anyone know of a solution to do this?
Solution 1:[1]
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
Solution 2:[2]
in config.yml
:
framework:
//
session:
//
cookie_lifetime: 3600 // was "lifetime" but deprecated
//
you can change this value ..
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Haythem Mrad |