• 周五. 3月 1st, 2024

    PHP设置session保存到redis中

    root

    11月 21, 2019 #session

    通过设置php.ini

    session.save_handler=redis
    session.save_path="tcp://xxx.rds.aliyuncs.com:6379?auth=redis密码"
    

    验证是否成功 新建测试文件test.php

    session_start();
    $_SESSION['username'] = "bianpeijiang"
    

    访问 curl -I http://localhost/test.php

    HTTP/1.1 200 OK
    Date: Fri, 20 Jan 2017 08:50:38 GMT
    Server: Apache
    Set-Cookie: PHPSESSID=tgt25hi24qfjs2f289941g8pm0; path=/
    Expires: Thu, 19 Nov 1981 08:52:00 GMT
    Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
    Pragma: no-cache
    Vary: Accept-Encoding
    Content-Type: text/html; charset=UTF-8
    

    连接redis查看

    > get "PHPREDIS_SESSION:tgt25hi24qfjs2f289941g8pm0"
    "username|s:12:\"bianpeijiang\";"
    

    通过实现SessionHandlerInterface 接口自定义session存储

    <?php
    class MySessionHandler implements SessionHandlerInterface
    {
        private $savePath;
    
        public function open($savePath, $sessionName)
        {
            $this->savePath = $savePath;
            if (!is_dir($this->savePath)) {
                mkdir($this->savePath, 0777);
            }
    
            return true;
        }
    
        public function close()
        {
            return true;
        }
    
        public function read($id)
        {
            return (string)@file_get_contents("$this->savePath/sess_$id");
        }
    
        public function write($id, $data)
        {
            return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
        }
    
        public function destroy($id)
        {
            $file = "$this->savePath/sess_$id";
            if (file_exists($file)) {
                unlink($file);
            }
    
            return true;
        }
    
        public function gc($maxlifetime)
        {
            foreach (glob("$this->savePath/sess_*") as $file) {
                if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
                    unlink($file);
                }
            }
    
            return true;
        }
    }
    
    $handler = new MySessionHandler();
    session_set_save_handler($handler, true);
    session_start();

    root

    发表回复