php的session默认是文件存储:
session.save_handler = files
session.save_path = "/var/lib/php/session"
当做web集群,需要session同步时,将session存到分布式memcache来达到共享同步是个不错的办法
方法:
第1种:
vi /etc/php.ini
session.save_handler = memcache
session.save_path = "tcp://192.168.20.193:11211,tcp://192.168.20.194:11211"
第2种:
在php文件中使用ini_set函数进行配置,适合无法修改配置文件的虚拟主机
<?php
....
ini_set("session.save_handler", "memcache");
ini_set("session.save_path", "tcp://192.168.20.193:11211,tcp://192.168.20.194:11211");
....
?>
重启web服务器
service httpd restart
查看phpinfo
测试
192.168.20.193中的login.php
<?php
session_start();
$_SESSION['login_time'] = time();
$_SESSION['username'] = 'test2';
$token=session_id();
echo $token;
//memache实现
$mem = new Memcache();
$mem->addServer('192.168.20.193',11211);
$mem->addServer('192.168.20.194',11211);
/*
//memached实现
$mem = new Memcached();
$servers = array(
array('192.168.20.193', 11211, 33),
array('192.168.20.194', 11211, 67)
);
$mem->addServers($servers);
*/
echo '<hr>';
print_r($mem->get($token));
?>
<div>
<a href="http://192.168.20.194/user.php?token=<?php echo $token;?>" target="_balnk">跳转到194网站的个人中心</a>
</div>
192.168.20.194中的user.php
<?php
$mem = new Memcache();
$mem->addServer('192.168.20.193',11211);
$mem->addServer('192.168.20.194',11211);
$token=$_GET['token'];//获取传过来的token
print_r($mem->get($token));
?>
<div>
<a href="http://192.168.20.193/user.php?token=<?php echo $token;?>" target="_balnk">返回193网站的个人中心</a>
</div>