php 如何以json格式儲存session,而不是預設的內建編碼?

來源:互聯網
上載者:User
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);    }}

可以考慮下寫庫

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.