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.

Example: www.domain.com

The downside to this is that the session data can't travel with you to other subdomains. So if you started a session on www.domain.com, the session data would become unavailable on forums.domain.com. 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: forums.domain.com -> .domain.com

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) {
 ini_set('session.cookie_domain',substr($_SERVER['SERVER_NAME'],strpos($_SERVER['SERVER_NAME'],".")));
}


2.除了设置session的domain外,还需要在所有的服务器上共享session的存储, 如果session是文件存储,则所有服务器应共享session存储目录,比如通过nfs或san等. 另外一个方法是将所有服务器的session保存到同一个DB;
分页: 1/1 第一页 1 最后页 [ 显示模式: 摘要 | 列表 ]