I am writing a chat module where anonymous users are able to chat with a logged in user via an external websockets connection.

I need an ID to uniquely distinguish the anonymous users and assign them to different connections and keep track of the status of the connection.

How do I (securely) get a unique user id or session id for an anonymous user ?

2 Answers 2


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

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

  • Is this the same sid used for drupal users ?
    – drcelus
    Commented Jul 18, 2014 at 9:58
  • 2
    Yeah, Drupal doesn't do anything particularly special with session IDs it just uses PHP's built-in session functions
    – Clive
    Commented Jul 18, 2014 at 10:01
  • 1
    Please note that Drupal is currently doing something special with session ids as described in the other answer to this question. Commented Aug 31, 2016 at 17:40

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() {
  $_SESSION['nosave'] = TRUE;

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.