方法一:修改配置文件
找到php.ini配置文件寞焙,修改如下參數(shù)
session.save_handler =redis
session.save_path="tcp://127.0.0.1:6379?auth=1234qwer"
session.php腳本測(cè)試
// 如果沒(méi)有修改配置文件,則可以使用如下代碼設(shè)置
// ini_set("session.save_handler","redis");
// ini_set("session.save_path","tcp://127.0.0.1:6379?auth=1234qwer");
ini_set('session.gc_maxlifetime',600);//設(shè)置過(guò)期時(shí)間為600秒
session_start();
$_SESSION['time'] = time();
$_SESSION['name'] = '李四';
echo $_SESSION['time']."<br>";
echo $_SESSION['name']."<br>";
echo session_id()."<br>";
echo 'php_session = '.json_encode($_SESSION['users']);
打印出來(lái):
1492074559
李四
6sv5ut17m6jq3fcf3khlcjtkd7
php_session = {"name":"ybl","age":60}
這樣的好處還有到了過(guò)期時(shí)間之后,redis會(huì)自動(dòng)把數(shù)據(jù)刪除
方法二:程序?qū)崿F(xiàn)
不修改配置文件稻艰,通過(guò)程序?qū)崿F(xiàn)尊勿。session.php腳本測(cè)試
ini_set("session.save_handler","redis");
ini_set("session.save_path","tcp://127.0.0.1:6379?auth=1234qwer");
session_start();
$_SESSION['users'] =array('name'=>'ybl','age'=>60);
$redis=newredis();
$redis->connect('127.0.0.1',6379);
$redis->auth("1234qwer");
//打印session_id
echo 'session_id = '.session_id();
//從redis獲取session(redis用session_id作為key,以string的形式存儲(chǔ))
echo 'redis_session = '.$redis->get('PHPREDIS_SESSION:'.session_id());
//php獲取session值
echo 'php_session = '.json_encode($_SESSION['users']);
打釉印:
session_id = jisieih1dmsqh28su4f4smmj30
redis_session = users|a:2:{s:4:"name";s:3:"ybl";s:3:"age";i:60;}
php_session = {"name":"ybl","age":60}