4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpKernel\EventListener;
14 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
15 use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
16 use Symfony\Component\HttpKernel\KernelEvents;
19 * Saves the session, in case it is still open, before sending the response/headers.
21 * This ensures several things in case the developer did not save the session explicitly:
23 * * If a session save handler without locking is used, it ensures the data is available
24 * on the next request, e.g. after a redirect. PHPs auto-save at script end via
25 * session_register_shutdown is executed after fastcgi_finish_request. So in this case
26 * the data could be missing the next request because it might not be saved the moment
27 * the new request is processed.
28 * * A locking save handler (e.g. the native 'files') circumvents concurrency problems like
29 * the one above. But by saving the session before long-running things in the terminate event,
30 * we ensure the session is not blocked longer than needed.
31 * * When regenerating the session ID no locking is involved in PHPs session design. See
32 * https://bugs.php.net/bug.php?id=61470 for a discussion. So in this case, the session must
33 * be saved anyway before sending the headers with the new session ID. Otherwise session
34 * data could get lost again for concurrent requests with the new ID. One result could be
35 * that you get logged out after just logging in.
37 * This listener should be executed as one of the last listeners, so that previous listeners
38 * can still operate on the open session. This prevents the overhead of restarting it.
39 * Listeners after closing the session can still work with the session as usual because
40 * Symfonys session implementation starts the session on demand. So writing to it after
41 * it is saved will just restart it.
43 * @author Tobias Schultze <http://tobion.de>
45 class SaveSessionListener implements EventSubscriberInterface
47 public function onKernelResponse(FilterResponseEvent $event)
49 if (!$event->isMasterRequest()) {
53 $session = $event->getRequest()->getSession();
54 if ($session && $session->isStarted()) {
59 public static function getSubscribedEvents()
62 // low priority but higher than StreamedResponseListener
63 KernelEvents::RESPONSE => array(array('onKernelResponse', -1000)),