php如何从序列化的mysql字符串中提取变量?

3wabscal  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(345)

在一个php文件中,我试图提取这个字符串中的用户名var

user_name|s:11:"testaccount";user_email|s:27:"testaccount@testaccount.com";user_login_status|i:1;

我不知道这是什么格式。我使用php mysqli来查询这个函数的数据库

$q = "SELECT `data` FROM `sessions` WHERE `id` = '".$this->dbc->real_escape_string($cookie)."' LIMIT 1";

其中$cookie是客户端的cookie。有人知道字符串的格式吗?

1cosmwyk

1cosmwyk1#

姓名、电子邮件和状态用分号分隔。名称和值由管道分隔。值为序列化形式。例如,用户名:11:“testaccount”;
非序列化s:11:“测试帐户”;您将获得testaccount值

qni6mghb

qni6mghb2#

我想出来了。使用此函数执行此操作https://gist.github.com/phred/1201412.

//
// This is the result of about an hour's delving into PHP's hairy-ass serialization internals.
// PHP provides a session_decode function, however, it's only useful for setting the contents of
// $_SESSION.  Say, for instance, you want to decode the session strings that PHP stores in its
// session files -- session_decode gets you nowhere.
//
// There are a bunch of nasty little solutions on the manual page[1] that use pretty hairy regular
// expressions to get the job done, but I found a simple way to use PHP's unserialize and recurse
// through the string extracting all of the serialized bits along the way.
//
// It's not speedy (it calls unserialize AND serialize for each session element), but it's accurate
// because it uses PHP's internal serialized object parser.  Fun trivia: PHP's serialized object
// parser is an ugly-ass little compiled regular expression engine.  But hey, it works, let's not
// reinvent this wheel.
//
// [1]: http://www.php.net/manual/en/function.session-decode.php
//

define("SESSION_DELIM", "|");

function unserialize_session($session_data, $start_index=0, &$dict=null) {
   isset($dict) or $dict = array();

   $name_end = strpos($session_data, SESSION_DELIM, $start_index);

   if ($name_end !== FALSE) {
       $name = substr($session_data, $start_index, $name_end - $start_index);
       $rest = substr($session_data, $name_end + 1);

       $value = unserialize($rest);      // PHP will unserialize up to "|" delimiter.
       $dict[$name] = $value;

       return unserialize_session($session_data, $name_end + 1 + strlen(serialize($value)), $dict);
   }

   return $dict;
}

$session_data = …; // A string from a PHP session store.

$session_dict = unserialize_session($session_data);

相关问题