I create module with many sessions . I want unset all session after module work . When I use session_destroy(); end of my module code , I have error and after that my sessions seem delete (session_unset(); not worked) . but after 4 or 5 time refresh page all sessions show to me .


Warning: session_destroy(): Trying to destroy uninitialized session in Drupal\...

How can I fix this problem in my drupal 8 ?


1 Answer 1


Don't use low level session_destroy(), use the session manager instead:


This will remove all session data and the user is logged out, if that's what you want. You still get a warning if there is no session, so you might want to check this first.

A better solution might be to use the symfony Session object

$request = \Drupal::request();

if you have set the session data in the request object or

$_SESSION = [];

if you have used the deprecated $_SESSION superglobal.

Normally you don't destroy the session or clear all session data, because there might be other modules that also use session data. Simply remove session variables in the same place where you have set them.

$request = \Drupal::request();
$session = $request->getSession();
$session->set('mymodule.value', $value);

// remove later when you don't need the value anymore

When all modules removed their values the session is destroyed by Drupal automatically (for anonymous users).

  • Very very thanks.Can I use this code to save data to session?Is it correct?
    – user60258
    Feb 18, 2017 at 15:58
  • 2
    The easiest way is to use $_SESSION['my_module']['key1'] = $data; to save the data and unset($_SESSION['my_module']); to remove the data again. Let Drupal handle the rest, like initializing and destroying the session.
    – 4uk4
    Feb 18, 2017 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy