기본 내장 인코딩 대신 json 형식으로 PHP 세션을 저장하는 방법은 무엇입니까?

WBOY
풀어 주다: 2023-03-01 17:12:02
원래의
1361명이 탐색했습니다.

php는 어떻게 기본 내장 인코딩 대신 json 형식으로 세션을 저장하나요?

조금 만지작거린 후에 session_save_handler가 자체 클래스나 메소드에 의해 재정의되더라도 쓰기 및 읽기의 들어오고 나가는 데이터는 여전히 직렬화되어 있으며 세션별 직렬화는 일반적인 직렬화가 아닙니다... 여전히 해결할 수 없습니다. Memcached 저장 문제가 json 형식입니다.

답글 내용:

php는 어떻게 기본 내장 인코딩 대신 json 형식으로 세션을 저장하나요?

조금 만지작거린 후에 session_save_handler가 자체 클래스나 메소드에 의해 재정의되더라도 쓰기 및 읽기의 들어오고 나가는 데이터는 여전히 직렬화되어 있으며 세션별 직렬화는 일반적인 직렬화가 아닙니다... 여전히 해결할 수 없습니다. Memcached 저장 문제가 json 형식입니다.

해결책을 찾았습니다:

<code><?php

namespace Lboy\Session\SaveHandler;

/**
 * Memcached JSON-formatted session save handler
 *
 * The default memcache session save handler stores sessions encoded with
 * session_encode, but the encoded session is not simple to parse in other
 * languages. Therefore, this class encodes the session in JSON to make reading
 * the session in other languages simple.
 *
 * Note: This class uses the newer php-memcached extension, not php-memcache!
 * @see http://php.net/manual/en/book.memcached.php
 *
 * @author Lee Boynton <lee@lboynton.com>
 */
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);
    }
}</code>
로그인 후 복사

라이브러리 작성을 고려해 볼 수 있습니다

관련 라벨:
php
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!