简体   繁体   中英

php store session in redis

I want to use Redis to store/retrieve session in PHP, so I create a new handler like this:

class RedisSessionHandler implements SessionHandlerInterface
{
    public $ttl = 1800; // 30 minutes default
    protected $db;
    protected $prefix;

    public function __construct(PredisClient $db, $prefix = 'PHPSESSID:') {
        $this->db = $db;
        $this->prefix = $prefix;
    }

    public function open($savePath, $sessionName) {
        // No action necessary because connection is injected
        // in constructor and arguments are not applicable.
    }

    public function close() {
        $this->db = null;
        unset($this->db);
    }

    public function read($id) {
        $id = $this->prefix . $id;
        $sessData = $this->db->get($id);
        $this->db->expire($id, $this->ttl);
        return $sessData;
    }

    public function write($id, $data) {
        $id = $this->prefix . $id;
        $this->db->set($id, $data);
        $this->db->expire($id, $this->ttl);
    }

    public function destroy($id) {
        $this->db->del($this->prefix . $id);
    }

    public function gc($maxLifetime) {
        // no action necessary because using EXPIRE
    }
}

and I set it as a handler

$db = new PredisClient();
$sessHandler = new RedisSessionHandler($db);
session_set_save_handler($sessHandler);
session_start();

In a real application, I'm using DI, and I have a SessionMiddleware where I'm setting and starting the session

And I'm getting the error like: Warning: session_start(): Failed to read session data: user (path: )

Is that mean I still need to set session.save_path = tcp://127.0.0.1:6379 in ini file? as for me it makes no sense as I passing Redis instance to the custom handler

I found the solution for this, you need return empty string in the read method in PHP 7.2 and newerhttps://www.php.net/manual/en/function.session-start.php#120589

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM