Using PHP sessions across subdomains

| |
[不指定 2009/12/03 10:47 | by ipaddr ]
By default, PHP uses the 'PHPSESSID' cookie to propagate session data across multiple pages, and by default it uses the current top-level domain and subdomain in the cookie declaration.


The downside to this is that the session data can't travel with you to other subdomains. So if you started a session on, the session data would become unavailable on The solution is to change the domain PHP uses when it sets the 'PHPSESSID' cookie.

Assuming you have an init file that you include at the top of every PHP page, you can use the ini_set() function. Just add this to the top of your init page:

ini_set('session.cookie_domain', substr($_SERVER['SERVER_NAME'],strpos($_SERVER['SERVER_NAME'],"."),100));

This line of code takes the domain and lops off the subdomain.

Example: ->

Now, every time PHP sets the 'PHPSESSID' cookie, the cookie will be available to all subdomains!

1. 以下代码可以优化如下:
//sessions across subdomains
if (strpos($_SERVER['SERVER_NAME'],".")!==false) {

2.除了设置session的domain外,还需要在所有的服务器上共享session的存储, 如果session是文件存储,则所有服务器应共享session存储目录,比如通过nfs或san等. 另外一个方法是将所有服务器的session保存到同一个DB;
Program | 评论(0) | 引用(0) | 阅读(4822)