[php] serialize, unserialize the session data in PHP

本文介绍如何使用 PHP 的 serialize_session 和 unserialize_session 函数进行 session 数据的序列化和反序列化,包括安全模式下的应用及特殊值处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值