php session存入redis
一、 安装phpredis扩展
php连接redis需要安装phpredis扩展。
下载地址:https://github.com/phpredis/phpredis/releases,选用相应版本。
笔者用的是php5.6.29,下载了phpredis-3.0.0安装出了问题,于是换成phpredis-2.2.8,正常。
# tar zxvf phpredis-2.2.8.tar.gz && cd phpredis-2.2.8
# /usr/local/php/bin/phpize
# ./configure --with-php-config=/usr/local/php/bin/php-config
# make && make install
正常情况下会提示在下面目录下生成redis.so文件
Installing shared extensions: /usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/
# sed -i '$aextension="redis.so"' /usr/local/php/etc/php.ini
# service httpd restart
验证:
# php -i | grep redis | grep -xq redis && echo ok || echo "phpredis extended failure"
二、 配置php连接redis(笔者使用的阿里云redis)
# sed -i 's/session.save_handler.*/session.save_handler = redis/' /usr/local/php/etc/php.ini
# sed -i '/session.save_handler/asession.save_path ="tcp://xxxx.rds.aliyuncs.com?auth=redis密码"' /usr/local/php/etc/php.ini
# service httpd restart
三、 验证session存储
1. 测试文件
# cat test.php
<?php echo "what are you doing now?"; session_start(); $_SESSION['a'] = 'elisun'; ?>
2. 访问
# curl -I http://127.0.0.1/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
3. 连接redis查看该key
> get "PHPREDIS_SESSION:tgt25hi24qfjs2f289941g8pm0"
"a|s:6:\"elisun\";"