You are here

function session_api_get_sid in Session API 7

Same name and namespace in other branches
  1. 5 session_api.module \session_api_get_sid()
  2. 6 session_api.module \session_api_get_sid()

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) {
  $sid =& drupal_static(__FUNCTION__);
  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_get_cookie_name()]) && $_COOKIE[session_api_get_cookie_name()]) {
      $session_id = $_COOKIE[session_api_get_cookie_name()];
    }
    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 0, the cookie will expire when the session ends
    // (i.e, when the browser closes).
    $expire = variable_get('session_api_cookie_expire_time', 2592000);
    $expire_timestamp = $expire == 0 ? 0 : REQUEST_TIME + $expire;

    // 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_get_cookie_name(), $session_id, $expire_timestamp, '/', $cookie_domain);
  }
  return $sid;
}