与子域共享PHP会话 [英] PHP session shared with subdomain

查看:61
本文介绍了与子域共享PHP会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了许多论坛(包括该论坛),这些论坛在子域之间传递会话变量,但我无法使其正常工作.有人可以解释我所缺少的吗?

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?

php.ini文件中:

session.cookie_domain = ".mydomain.example"

已通过phpinfo()验证我正在使用正确的php.ini文件

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

www.mydomain.example的页面中设置会话变量$_SESSION['a'],通过在下一页调用它来验证它是否出现(确实如此).点击链接到sub.mydomain.example.

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.

位于sub.mydomain.example的页面检查是否使用以下方式设置了会话变量:

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?

推荐答案

您必须将会话ID作为Cookie传递,并在新域上设置相同的会话ID

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

这篇关于与子域共享PHP会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆