Sharing session variables in PHP between subdomains

感情迁移 提交于 2020-01-16 00:53:10

问题


I want to share my session variables in PHP using many subdomains. I have that example :

  • example.com
  • subdomain1.example.com

I try to use the same session variables between the two domains. I already tested a lot of functions in PHP but nothing work. Here is my way to test :

On the example.com/page.php, I have that test :

echo '<pre>';
var_dump(session_set_cookie_params(0, '/', '.example.com')); 
session_start(); 
echo "Session ID : ".session_id()."\n";
$_SESSION['foo'] = 'bar';
print_r($_SESSION);

And on subdomain1.example.com/page.php, I have that one :

echo '<pre>';
session_set_cookie_params(0, '/', '.example.com');
session_start();
echo "Session ID : ".session_id()."\n";
print_r($_SESSION);

I can see that the session id is the same between the two pages, but session variables are impossible to read in subdomain1.example.com/page.php

I tested many functions, like set a name to the session, but with no more results.

Thank you.


回答1:


The only way I can think of to do this would be to save the session data to a cookie, then open the cookie when the other domain is accessed. You can read how to do this here: http://www.depiction.net/tutorials/php/cookies-session-variables.php

Out of curiosity, why do you want to do this?




回答2:


If you want to avoid using a cookie based solution, and both domains can access the same database, I'd be storing the session in the database instead of the filesystem:

Here's an exmaple in the comments for the session at php.net: http://php.net/manual/en/book.session.php




回答3:


If storing in a cookie is not possible, you can use a shared cache layer. This can be a database such as MySQL, or even use an APC (if it's being served by the same server). You can also use memcache. Memcache based sessions are faster than using a database. More information on the memcache session store can be found here:

http://php.net/manual/en/memcached.sessions.php




回答4:


The following code is tested and working, without the requirement for direct cookie manipulation (other than the session itself), or anything complex like Memcache/DB storage.

ini_set('session.cookie_domain', '.sonassi.com' );
session_name('sonassi');
session_start();

Just make sure that the session_save_path is accessible by both domains.



来源:https://stackoverflow.com/questions/9814400/sharing-session-variables-in-php-between-subdomains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!