PHP 多域会话;ini_set 不工作?

2022-01-04 00:00:00 session php dns ini-set

我正在尝试设置它,因此如果您登录到我的网站,会话会转移到我网站的所有子域.例如,如果您转到 domain.com 并登录,然后转到 sub.domain.com,则您已经在 sub.domain.com 上登录了.

I'm trying to set it up so if you log in to my website the session carries over to all sub-domains of my website. For example, if you go to domain.com and log in, then go to sub.domain.com, you'll already be logged in at sub.domain.com.

据我所知,您可能想使用 ini_set('session.cookie_domain','.domain.com') 然后 session_start(),然后设置会话变量,但这不起作用.

To my understanding, you would want to use ini_set('session.cookie_domain','.domain.com') and then session_start(), then set your session variables, but this isn't working.

我正在做的事情的例子:

Example of what I'm doing:

domain.com 的代码:

Code for domain.com:

<?php
 ini_set('session.cookie_domain','.domain.com');
 session_start();
 $_SESSION['variable'] = 1;
?>

sub.domain.com 的代码:

Code for sub.domain.com:

<?php
 session_start();
 echo $_SESSION['variable'];
?>

但是 $_SESSION['variable'] 没有设置.

But $_SESSION['variable'] isn't set.

我也试过在 sub.domain.com 代码中使用 ini_set(),但没有任何区别.我已经通过使用 ini_get() 验证了设置 session.cookie_domain 是否有效.

I've also tried using ini_set() in the sub.domain.com code, but it made no difference. I've verified that setting session.cookie_domain is working by using ini_get().

我做错了什么?谢谢!

推荐答案

先验证ini_set

<?php
ini_set('session.cookie_domain','.domain.com');

echo ini_get('session.cookie_domain');

session_start();  
$_SESSION['variable'] = 1; 

?> 

<小时>

更新:

刚刚想了一下..你也试过吗:

Just thought about it.. Did you also try:

<?php

session_set_cookie_params( 0, "/", ".domain.com", false, false); 
session_start();  
$_SESSION['variable'] = 1; 

?> 

<小时>

更新 2:替代处理(手动 cookie 处理)


Update 2: ALternate handling (manual cookie handling)

<?php

session_start();  
session_regenerate_id();
$_SESSION['variable'] = "String Test";

setcookie('PHPSESSID',session_id(),time()+86400,'/','.domain.com');
echo session_id();
?> 

并在子域文件中

<?php  
if (isset($_COOKIE['PHPSESSID']) && !empty($_COOKIE['PHPSESSID'])) session_id($_COOKIE['PHPSESSID']);

session_start();  
echo $_SESSION['variable'] . "<br />"; 
echo $_COOKIE['PHPSESSID'] . "<br />";
echo session_id();
?> 

<小时>

您可以在每个文件中添加三行来传递/处理会话信息


Three lines you could add to every file to hand off / handle session info

if (isset($_COOKIE['PHPSESSID']) && !empty($_COOKIE['PHPSESSID'])) session_id($_COOKIE['PHPSESSID']);
session_start();  
if (!isset($_COOKIE['PHPSESSID'])) setcookie('PHPSESSID',session_id(),time()+86400,'/','.domain.com');

您通过会话传递了哪些信息?或者你用它来处理登录等?

What info are you passing through the session? Or are you using it to handle logins, etc?

相关文章