[php] serialize, unserialize the session data in PHP

來源:互聯網
上載者:User
As we know, in PHP, we can use session_encode() and session_decode() to encode/decode the session data, but, if you have tried these two

functionality, you will see the they are not going as you think. So here, i find these two functionality which will help you to do that.

/* *
* serialize session
*
* @param array $data
* @param boolean $safe
* @return string
*/
function serialize_session( $array, $safe = true)
{
// the session is passed as refernece, even if you dont want it to
if ( $safe)
{
$array = unserialize( serialize( $array));
}

$raw = '';
$line = 0;
$keys = array_keys( $array);
foreach ( $keys as $key)
{
$value = $array[ $key];
$line++;
$raw .= $key . '|';
if ( is_array( $value) && isset( $value['huge_recursion_blocker_we_hope']))
{
$raw .= 'R:' . $value['huge_recursion_blocker_we_hope'] . ';';
}
else
{
$raw .= serialize( $value);
}
$array[ $key] = Array('huge_recursion_blocker_we_hope' => $line);
}

return $raw;
}

/* *
* unserialize session
*
* @param string $data
* @return array
*/
function unserialize_session( $data)
{
$vars = preg_split('/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff^|]*)\|/', $data, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
for ( $i = 0; $vars[ $i]; $i++)
{
$result[ $vars[ $i++]] = unserialize( $vars[ $i]);
}
return $result;
}

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.