Drupal - How to get an anonymous user session id?

You're looking for PHP's session_id():

session_id() is used to get or set the session id for the current session.


Drupal stopped tracking anonymous sessions a few versions ago. If you want to trick Drupal into doing it again you need to make a module with a custom hook_init() implementation.

/**
 * Implements hook_init().
 *
 * <soapbox>The Drupal team decided to remove support for anonymous user sessions
 * starting in Drupal 7.37. This fundamentally breaks several things related to Drupal.
 * I cannot find any documentation of this change in any changeme dating back to 7.33.
 * The answer comes to us from:</soapbox>
 *
 * https://dgtlmoon.com/drupal_7_anonymous_sessions
 */
function mymodule_init() {
  drupal_session_start();
  $_SESSION['nosave'] = TRUE;
}

Tags:

Sessions