简体   繁体   English

与子域共享PHP会话

[英]PHP session shared with subdomain

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 第1步

In the php.ini file: php.ini文件中:

session.cookie_domain = ".mydomain.example"

Verified with phpinfo() that I am using the right php.ini file phpinfo()验证,我正在使用正确的php.ini文件

Step 2 第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). www.mydomain.example页面中,设置会话变量$_SESSION['a'] ,通过在下一页调用它来验证它是否出现(确实如此)。 Click link to sub.mydomain.example . 单击链接到sub.mydomain.example

Step 3 第三步

Page at sub.mydomain.example checks if session variable is set using: sub.mydomain.example页面检查是否使用以下命令设置了会话变量:

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

Unfortunately I am getting my error message. 不幸的是,我收到错误消息。 What am I missing? 我想念什么?

You must pass the session id as a cookie and set the same session id on the new domain 您必须将会话ID作为Cookie传递,并在新域上设置相同的会话ID

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']); 
}

So, I went a different direction and used this entry which worked... 所以,我转向了另一个方向,并使用了这个有效的条目...

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

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. 首先,您必须查看HTTP标头,以查看发生了什么以及实际设置了哪些Cookie。 You can use LiveHTTPHeaders Firefox addon or something. 您可以使用LiveHTTPHeaders Firefox插件或其他工具。 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 它可能显示Cookie被浏览器发送回-因此可以确定这是服务器端问题

To see the actual result of your code (instead of guessing based on the indirect consequences) always helps. 查看代码的实际结果 (而不是根据间接结果进行猜测)总是有帮助的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM