function session_api_get_sid

7.x-1.x session_api.module session_api_get_sid($create = TRUE)

Returns the current session's Session ID.

Parameters

bool $create: (optional) A boolean indicating whether the session needs to be created if it doesn't exist yet. Defaults to TRUE.

Return value

Returns a positive integer with the Session ID when it exists. If not, there are 2 possible return values:

  • -1. This indicates that no session exists and none was created.
  • FALSE. This indicates that Session API is unavailable.

See also

drupal_session_initialize()

2 calls to session_api_get_sid()
SessionApiTestCase::testFunctions in ./session_api.test
Verify functions work properly.
session_api_test_init in tests/session_api_test.module
Implementation of hook_init().

File

./session_api.module, line 41
Session API provides an interface for storing information in the session.

Code

function session_api_get_sid($create = TRUE) {
  static $sid;

  if ($create) {
    // Must initialize sessions for anonymous users.
    session_api_start_session();
  }

  if (!session_api_available()) {
    return FALSE;
  }

  if (!isset($sid) || !$sid) {
    $sid = FALSE;

    // First, check if we already have an active session.
    if (isset($_COOKIE['session_api_session']) && $_COOKIE['session_api_session']) {
      $session_id = $_COOKIE['session_api_session'];
    }
    // If the caller doesn't want to create a new session if it didn't exist,
    // then return here.
    elseif (!$create) {
      // Return a negative value here, since it won't collide with any
      // session_api IDs.
      return -1;
    }
    else {
      $session_id = drupal_hash_base64(uniqid(mt_rand(), TRUE));
    }

    // Set expiration time. If -1, then use an expiration time of 0, which will
    // cause the cookie to expire when the session ends (i.e, when the browser
    // closes).
    $seconds = variable_get('session_api_cookie_expire_time', 2592000);
    $expire = $seconds === -1 ? REQUEST_TIME + $seconds : 0;

    // Update the session timeout.
    db_merge('session_api')->key(array('session_id' => $session_id))->fields(array('timestamp' => REQUEST_TIME))->execute();

    // Retrieve the sid.
    $query = db_select('session_api', 'sap');
    $query->fields('sap', array('sid'));
    $query->condition('session_id', $session_id);
    $sid = $query->execute()->fetchField();

    // Set cookie using the same domain that Drupal's own session cookie uses.
    $cookie_domain = ini_get('session.cookie_domain');
    setcookie('session_api_session', $session_id, $expire, '/', $cookie_domain);
  }

  return $sid;
}