php中将数据存储在session中的时候,会根据配置进行序列化,session_decode函数可以将session中的数据解码并重新存入$_SESSION这个全局变量中。但是如果仅仅需要解码后的数据,不需要重新存储到session中,就需要自己单独写函数来进行解码操作,具体代码如下:
// 请求入口
public function actionIndex($s_id='') {
$session_id = $s_id;
// '37qlrtm2vupsv6vmmi9nlbmdp5';
$data = Yii::app()->session->readSession($session_id);
$session_data = self::unserialize($data);
echo CJSON::encode($session_data);
}
private static function unserialize($session_data) {
$method = ini_get("session.serialize_handler");
switch ($method) {
case "php":
return self::unserialize_php($session_data);
break;
case "php_binary":
return self::unserialize_phpbinary($session_data);
break;
default:
throw new Exception("Unsupported session.serialize_handler: " . $method . ". Supported: php, php_binary");
}
}
private static function unserialize_php($session_data) {
$return_data = array();
$offset = 0;
while ($offset < strlen($session_data)) {
if (!strstr(substr($session_data, $offset), "|")) {
throw new Exception("invalid data, remaining: " . substr($session_data, $offset));
}
$pos = strpos($session_data, "|", $offset);
$num = $pos - $offset;
$varname = substr($session_data, $offset, $num);
$offset += $num + 1;
$data = unserialize(substr($session_data, $offset));
$return_data[$varname] = $data;
$offset += strlen(serialize($data));
}
return $return_data;
}
private static function unserialize_phpbinary($session_data) {
$return_data = array();
$offset = 0;
while ($offset < strlen($session_data)) {
$num = ord($session_data[$offset]);
$offset += 1;
$varname = substr($session_data, $offset, $num);
$offset += $num;
$data = unserialize(substr($session_data, $offset));
$return_data[$varname] = $data;
$offset += strlen(serialize($data));
}
return $return_data;
}