PHP 使用 Redis 保存 Session

vi /etc/php.ini
session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379"
session.gc_maxlifetime = 1440

修改php-fpm.conf
PHP-FPM的配置文件/etc/php-fpm.conf或者/etc/php-fpm.d/*.conf中,可能也有session的配置。
它们的session配置优先级比php.ini高,会覆盖php.ini中的配置。
php_value[session.save_handler] = files
php_value[session.save_path]    = /var/lib/php/session
如果用php.ini的配置,则需要把这两行用;注释掉。

systemctl restart php-fpm



test:
session_start();
$_SESSION['test_session']= @array('name' =>'aaa', 'abc'=>'hello');
echo 'session_id:' . session_id() . "\n";

$redis = new Redis();
$connSuccess = $redis->pconnect("127.0.0.1", "6379");
if ($connSuccess != true) {
    echo '{"code":2,"msg":"Connect Cache fail."}';
    exit();
}
echo 'PHPREDIS_SESSION:';
echo $redis->get('PHPREDIS_SESSION:' . session_id());
echo "\n";

echo '$_SESSION:';
var_dump($_SESSION['test_session']);
echo "\n";
exit();


redis-cli
> keys *
it will show:
1) "PHPREDIS_SESSION:9d82lcvkvbn4tirtntef8rq91e"