thinkPHP多域名情况下使用memcache方式共享session数据的实现方法
本文实例讲述了thinkPHP多域名情况下使用memcache方式共享session数据的实现方法。分享给大家供大家参考,具体如下:
一、问题起源
稍大一些的网站,通常都会有好几个服务器,每个服务器运行着不同功能的模块,使用不同的二级域名,而一个整体性强的网站,用户系统是统一的,即一套用户名、密码在整个网站的各个模块中都是可以登录使用的。各个服务器共享用户数据是比较容易实现的,只需要在后端放个数据库服务器,各个服务器通过统一接口对用户数据进行访问即可。但还存在一个问题,就是用户在这个服务器登录之后,进入另一个服务器的别的模块时,仍然需要重新登录,这就是一次登录,全部通行的问题,映射到技术上,其实就是各个服务器之间如何实现共享SESSION数据的问题。
二、PHPSESSION的工作原理
在解决问题之前,先来了解一下PHPSESSION的工作原理。在客户端(如浏览器)登录网站时,被访问的PHP页面可以使用session_start()打开SESSION,这样就会产生客户端的唯一标识SESSIONID(此ID可通过函数session_id()获取/设置)。SESSIONID可以通过两种方式保留在客户端,使得请求不同的页面时,PHP程序可以获知客户端的SESSIONID;一种是将SESSIONID自动加入到GET的URL中,或者POST的表单中,默认情况下,变量名为PHPSESSID;另一种是通过COOKIE,将SESSIONID保存在COOKIE中,默认情况下,这个COOKIE的名字为PHPSESSID。这里我们主要以COOKIE方式进行说明,因为应用比较广泛。
那么SESSION的数据保存在哪里呢?当然是在服务器端,但不是保存在内存中,而是保存在文件或数据库中。默认情况下,php.ini中设置的SESSION保存方式是files(session.save_handler=files),即使用读写文件的方式保存SESSION数据,而SESSION文件保存的目录由session.save_path指定,文件名以sess_为前缀,后跟SESSIONID,如:sess_c72665af28a8b14c0fe11afe3b59b51b。文件中的数据即是序列化之后的SESSION数据了。如果访问量大,可能产生的SESSION文件会比较多,这时可以设置分级目录进行SESSION文件的保存,效率会提高很多,设置方法为:session.save_path=”N;/save_path”,N为分级的级数,save_path为开始目录。当写入SESSION数据的时候,PHP会获取到客户端的SESSION_ID,然后根据这个SESSIONID到指定的SESSION文件保存目录中找到相应的SESSION文件,不存在则创建之,最后将数据序列化之后写入文件。读取SESSION数据是也是类似的操作流程,对读出来的数据需要进行解序列化,生成相应的SESSION变量。
三、多服务器共享SESSION的主要障碍及解决办法
通过了解SESSION的工作原理,我们可以发现,在默认情况下,各个服务器会各自分别对同一个客户端产生SESSIONID,如对于同一个用户浏览器,A服务器产生的SESSIONID是30de1e9de3192ba6ce2992d27a1b6a0a,而B服务器生成的则是c72665af28a8b14c0fe11afe3b59b51b。另外,PHP的SESSION数据都是分别保存在本服务器的文件系统中。
确定了问题所在之后,就可以着手进行解决了。想要共享SESSION数据,那就必须实现两个目标:一个是各个服务器对同一个客户端产生的SESSIONID必须相同,并且可通过同一个COOKIE进行传递,也就是说各个服务器必须可以读取同一个名为PHPSESSID的COOKIE;另一个是SESSION数据的存储方式/位置必须保证各个服务器都能够访问到。简单地说就是多服务器共享客户端的SESSIONID,同时还必须共享服务器端的SESSION数据。
第一个目标的实现其实很简单,只需要对COOKIE的域(domain)进行特殊地设置即可,默认情况下,COOKIE的域是当前服务器的域名/IP地址,而域不同的话,各个服务器所设置的COOKIE是不能相互访问的,如www.aaa.com的服务器是不能读写www.bbb.com服务器设置的COOKIE的。这里我们所说的同一网站的服务器有其特殊性,那就是他们同属于同一个一级域,如:tieba.xiaoyuan.com和www.xiaoyuan.com都属于域.xiaoyuan.com,那么我们就可以设置COOKIE的域为.xiaoyuan.com,这样tieba.xiaoyuan.com、www.xiaoyuan.com等等都可以访问此COOKIE。PHP代码中的设置方法如下:
<?php ini_set('session.cookie_domain','.xiaoyuan.com'); ?>
这样各个服务器共享同一客户端SESSIONID的目的就达到了。
第二个目标的实现可以使用文件共享方式,有2种方式可以解决,一是用数据库存session,还有就是试用memcache。这里用MEMCACHE来解决.
我用的是thinkphp框架,已经支持memcache方式存取session.架好memcache服务器后,只需要在配置文件里面设置好memcache的IP和端口,然后指定COOKIE_DOMAIN参数就可以了,然后就可以按正常操作session的方式进行操作,这时已经可以多域名共享session了
更多关于thinkPHP相关内容感兴趣的读者可查看本站专题:《ThinkPHP入门教程》、《thinkPHP模板操作技巧总结》、《ThinkPHP常用方法总结》、《smarty模板入门基础教程》及《PHP模板技术总结》。
希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。