2

I'm trying to change cookie_lifetime dynamically in my D8 project, to set cookie_lifetime to 0 or to some value(for example 24 hours). I know that this can be partially acomplished by changing cookie_lifetime variable in sites/default/services.yml, but this is not my case.

I've tried to use this answer but looks like it works only when I use start() method of the session manager.

So how do I change dynamically cookie_lifetime for existing session? Any answers appreciated, thanks in advance!

1 Answer 1

4

You can override SessionConfiguration::getOptions to set the cookie lifetime dynamically:

/mymodule/src/MySessionConfiguration.php:

<?php

namespace Drupal\mymodule;

use Drupal\Core\Session\SessionConfiguration;
use Symfony\Component\HttpFoundation\Request;

/**
 * Sets session cookie lifetime dynamically.
 */
class MySessionConfiguration extends SessionConfiguration {

  /**
   * {@inheritdoc}
   */
  public function getOptions(Request $request) {
    $options = parent::getOptions($request);

    // Set the cookie lifetime dynamically depending on the request.
    $options['cookie_lifetime'] = 30;

    return $options;
  }

}

Swap the service class in the container:

/mymodule/src/MymoduleServiceProvider.php:

<?php

namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

/**
 * Modifies the service.
 */
class MymoduleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('session_configuration');
    $definition->setClass('Drupal\mymodule\MySessionConfiguration');
  }

}

See Altering existing services, providing dynamic services.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.