You are here

function session_api_get_sid in Session API 6

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

Return a Session API ID corresponding to the current session. The session id is a created using the same method as Drupal 7 core as defined in includes/session.inc.

Parameters

boolean create set this to FALSE if you don't want to create a session: cookie if it doesn't already exist.

1 call to session_api_get_sid()
SessionApiTestCase::testFunctions in ./session_api.test
Verify functions.

File

./session_api.module, line 36
The Session API module provides a quick interface for storing information in the session.

Code

function session_api_get_sid($create = TRUE) {
  static $sid;
  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'];
      $sid = db_result(db_query("SELECT sid FROM {session_api} WHERE session_id = '%s'", array(
        ':session_id' => $session_id,
      )));
    }
    else {
      if (!$create) {

        // Return a negative value here, since it won't collide with any
        // session_api IDs.
        return -1;
      }
      else {
        $data = uniqid(mt_rand(), true);
        $hash = base64_encode(hash('sha256', $data, TRUE));
        $hash = strtr($hash, array(
          '+' => '-',
          '/' => '_',
          '=' => '',
        ));
        $session_id = $hash;
      }
    }

    // For the cookie we use the same domain that Drupal's own session cookie uses.
    $cookie_domain = ini_get('session.cookie_domain');

    // Update the session timeout.
    if ($sid) {
      $rec = new stdClass();
      $rec->sid = $sid;
      $rec->session_id = $session_id;
      drupal_write_record('session_api', $rec, 'sid');
      setcookie('session_api_session', $session_id, time() + variable_get('session_api_cookie_expire_time', 2592000), '/', $cookie_domain);
    }
    else {
      $rec = new stdClass();
      $rec->session_id = $session_id;
      drupal_write_record('session_api', $rec);
      $sid = $rec->sid;

      // Set cookie.
      setcookie('session_api_session', $session_id, time() + variable_get('session_api_cookie_expire_time', 2592000), '/', $cookie_domain);
    }
  }
  return $sid;
}