PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

php 如何以json格式存储session,而不是默认的内置编码?

原创
2023-03-01 17:12:02 1121浏览

php 如何以json格式存储session,而不是默认的内置编码?

折腾了下,即使session_save_handler被自己的类或者方法重写,write与read的出入数据都还是被序列化的,而且被session序列化不是一般的序列化...还是不能解解决memcached保存session数据为json的格式

回复内容:

php 如何以json格式存储session,而不是默认的内置编码?

折腾了下,即使session_save_handler被自己的类或者方法重写,write与read的出入数据都还是被序列化的,而且被session序列化不是一般的序列化...还是不能解解决memcached保存session数据为json的格式

找到了方案:


 */
class Memcached
{
    /**
     * @var \Memcached
     */
    protected $memcached;

    /**
     * Create new memcached session save handler
     * @param \Memcached $memcached
     */
    public function __construct(\Memcached $memcached)
    {
        $this->memcached = $memcached;
    }

    /**
     * Close session
     *
     * @return boolean
     */
    public function close()
    {
        return true;
    }

    /**
     * Destroy session
     *
     * @param string $id
     * @return boolean
     */
    public function destroy($id)
    {
        return $this->memcached->delete("sessions/{$id}");
    }

    /**
     * Garbage collect. Memcache handles this with expiration times.
     *
     * @param int $maxlifetime
     * @return boolean Always true
     */
    public function gc($maxlifetime)
    {
        // let memcached handle this with expiration time
        return true;
    }

    /**
     * Open session
     *
     * @param string $savePath
     * @param string $name
     * @return boolean
     */
    public function open($savePath, $name)
    {
        // Note: session save path is not used
        $this->sessionName = $name;
        $this->lifetime = ini_get('session.gc_maxlifetime');
        return true;
    }

    /**
     * Read session data
     *
     * @param string $id
     * @return string
     */
    public function read($id)
    {
        $_SESSION = json_decode($this->memcached->get("sessions/{$id}"), true);

        if (isset($_SESSION) && !empty($_SESSION) && $_SESSION != null)
        {
            return session_encode();
        }

        return '';
    }

    /**
     * Write session data
     *
     * @param string $id
     * @param string $data
     * @return boolean
     */
    public function write($id, $data)
    {
        // note: $data is not used as it has already been serialised by PHP,
        // so we use $_SESSION which is an unserialised version of $data.
        return $this->memcached->set("sessions/{$id}", json_encode($_SESSION),
            $this->lifetime);
    }
}

可以考虑下写库

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。