You are here

7 会话阶段

admin 的头像
Submitted by admin on 星期五, 2015-07-24 09:51

作者:老葛,北京亚艾元软件有限责任公司,http://www.yaiyuan.com

我们来看阶段4,也就是会话阶段,对应的代码:

 case DRUPAL_BOOTSTRAP_SESSION:

     require_once DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');

     drupal_session_initialize();

     break;

在这里,首先加载includes/session.inc 文件,然后调用drupal_session_initialize函数。drupal_session_initialize函数就位于includes/session.inc文件中,我们通过文本查找,很快就找到了这个函数的定义:

/**

 * Initializes the session handler, starting a session if needed.

 */

function drupal_session_initialize() {

  global $user, $is_https;

 

  session_set_save_handler('_drupal_session_open', '_drupal_session_close', '_drupal_session_read', '_drupal_session_write', '_drupal_session_destroy', '_drupal_session_garbage_collection');

 

  // We use !empty() in the following check to ensure that blank session IDs

  // are not valid.

  if (!empty($_COOKIE[session_name()]) || ($is_https && variable_get('https', FALSE) && !empty($_COOKIE[substr(session_name(), 1)]))) {

    // If a session cookie exists, initialize the session. Otherwise the

    // session is only started on demand in drupal_session_commit(), making

    // anonymous users not use a session cookie unless something is stored in

    // $_SESSION. This allows HTTP proxies to cache anonymous pageviews.

    drupal_session_start();

    if (!empty($user->uid) || !empty($_SESSION)) {

      drupal_page_is_cacheable(FALSE);

    }

  }

  else {

    // Set a session identifier for this request. This is necessary because

    // we lazily start sessions at the end of this request, and some

    // processes (like drupal_get_token()) needs to know the future

    // session ID in advance.

    $GLOBALS['lazy_session'] = TRUE;

    $user = drupal_anonymous_user();

    // Less random sessions (which are much faster to generate) are used for

    // anonymous users than are generated in drupal_session_regenerate() when

    // a user becomes authenticated.

    session_id(drupal_hash_base64(uniqid(mt_rand(), TRUE)));

    if ($is_https && variable_get('https', FALSE)) {

      $insecure_session_name = substr(session_name(), 1);

      $session_id = drupal_hash_base64(uniqid(mt_rand(), TRUE));

      $_COOKIE[$insecure_session_name] = $session_id;

    }

  }

  date_default_timezone_set(drupal_get_user_timezone());

}

session_set_save_handler用来初始化会话处理器,包括会话的打开、关闭、读取、写入、销毁、垃圾收集。接下来检查会话是否存在,如果会话已经存在,那么启动会话;如果会话不存在,那么生成会话。我们这里看到函数drupal_hash_base64,这是Drupal的加密算法,采用base64的哈希算法。uniqid用来生成一个唯一的ID号。session_id用来设置会话的ID号。


Drupal版本: