When you set a Drupal session variable (i.e. a "magic" variable you may set like this):

$_SESSION['mymodule'] = array('key' => 'value');

the value goes away when the user logs out.

If you set a cookie, using the function


the value saved survives the user session.

However, I wonder if they just two of a kind (i.e. a Drupal session variable is just a cookie, but with the lifetime restricted to the duration of a the session.

Or is a Drupal session variable not implemented using a session cookie?


1 Answer 1


Seeing this has two votes, I'll try to explain it.

Drupal uses the built-in PHP session mechanism, which as you rightly suspect is based on a cookie. The cookie name is SESS followed by a long string of characters, and its value is another long string of characters. PHP detects this cookie and makes it available to Drupal's session implementation, which by default uses the database table sessions for storage, with the value of the cookie as the key sid.

The session entry also records the user ID: early in the Drupal bootstrap sequence the session is loaded and then the corresponding user object, which is subsequently used to govern access to resources, based on the user's roles and other attributes.

Data stored in the PHP global array $_SESSION is automatically saved to the current session's database entry by Drupal at the end of a page request. This is typically used to store relatively transient data such as items in a shopping cart.

Other cookies can be saved and retrieved in code (including JavaScript) and they will not be affected by logout unless you specifically write code to delete them when that happens. Confusingly, cookies with an expiry time of 0 are also often termed "session cookies" - these are deleted when you shut down your browser.

There's a lot more that could be said and I'll add some good references when I have a chance.

  • Thanks! This is exactly the type of information I was looking for. It cleared up several things that confused me. Basically, I am trying to figure out the best mechanism for a Drupal website to keep track of state across page loads. Not a shopping cart, but very similar. Aug 15, 2018 at 13:40
  • 1
    @FreeRadical generally for that requirement session data is your best bet. In Drupal 8 there's the private tempstore which is a wrapper round session data in the default case: api.drupal.org/api/drupal/… Aug 15, 2018 at 13:54

Your Answer

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

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