开发者

Sharing $_SESSION variables across subdomains using PHP

I am trying to share the contents of the s开发者_StackOverflowession variable across two subdomains but for some reason it is not working.

The sessionid is exactly the same on both subdomains but the variables aren't available.

I can achieve this with Cookies and this is working but would rather use the values in the session.

Here is how I'm setting the domain for the session:

Thanks, Scott

UPDATE Sorry should have said, I am already using the following:

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

if(session_id ==''){session_start();}


You are looking for this function: session_set_cookie_params(). Say you have two domains:

  1. site1.example.com
  2. site2.example.com

In order to share your session data across both domains, call the following functiontion before session_start():

session_set_cookie_params(0, '/', '.example.com');

(Edit: indeed I forgot a dot in the example code)


The sessionid is exactly the same on both subdomains (..)

Are you sure that the value (not the name) of sessionid is the same?

I needed similar thing 2 years ago, but I needed it to work on completely different virtual hosts (e.g., example.com and something.else.net), so I wrote a small script that ensures that user gets the same session_id on different virtual hosts. Source code is available at http://www.misc.lv/_downloads_file.php?id=18, but there's small bug on line 58 - arguments of strpos() should be swapped (I'm too lazy to fix it and upload fixed script).

Basic requirements/steps are:

  1. all pages should be on the same server, as they need a common "storage" for session variables;
  2. there must be one "main" host; there's no limit on a number of "additional" hosts;
  3. if currently opened page is on the "main host" (and it is not a request of session_id), nothing "extraordinary" has to be done;
  4. if page is not on the "main host" and there is an active session, nothing "extraordinary" has to be done, as session_id probably has already been shared;
  5. if page is not on the "main host" and there is no active session, request a session_id from the "main host".
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜