PHP session shared with subdomain

£可爱£侵袭症+ 提交于 2019-12-18 05:23:15

问题


I have read many forums (including this one) about passing session variables between subdomains, and I can't get this to work. Can someone explain what I am missing?

Step 1

In the php.ini file:

session.cookie_domain = ".mydomain.example"

Verified with phpinfo() that I am using the right php.ini file

Step 2

In page at www.mydomain.example set a session variable $_SESSION['a'], verify that it appears by calling it on the next page (it does). Click link to sub.mydomain.example.

Step 3

Page at sub.mydomain.example checks if session variable is set using:

$a = $_SESSION['a'];
if(!isset($_SESSION['a'])){
    echo "Error: Session Variable not available";
}

Unfortunately I am getting my error message. What am I missing?


回答1:


You must pass the session id as a cookie and set the same session id on the new domain

For example you can use this code

ini_set('session.cookie_domain', '.example.com');
$currentCookieParams = session_get_cookie_params();

$rootDomain = '.example.com';
session_set_cookie_params( 
    $currentCookieParams["lifetime"], 
    $currentCookieParams["path"], 
    $rootDomain, 
    $currentCookieParams["secure"], 
    $currentCookieParams["httponly"] 
); 

if(!empty($_SESSION)){
    $cookieName = session_id();
    setcookie('PHPSESSID', $cookieName, time() + 3600, '/', $rootDomain); 

}

if(isset($_COOKIE['PHPSESSID'])){
    session_name($_COOKIE['PHPSESSID']); 
}



回答2:


So, I went a different direction and used this entry which worked...

session_set_cookie_params(0, '/', '.mydomain.example');
session_start();



回答3:


debugging.
is the thing you're missing.

first of all you have to watch HTTP headers to see what is going on and what cookies actually being set. You can use LiveHTTPHeaders Firefox addon or something. With such info you can find the problem. Without it noone can answer tour question "my sessions don't work"

It can prove your statement of proper domain setting in the session settings. Or disprove it.
It can reveal some other misconfiguring.
It may show you cookie being sent back by the browser - so you can be sure that is server side problem

To see the actual result of your code (instead of guessing based on the indirect consequences) always helps.



来源:https://stackoverflow.com/questions/2835486/php-session-shared-with-subdomain

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