1

According to Allow php sessions to carry over to subdomains, there are 3 ways to allow PHP sessions across different subdomains.

  • php.ini: session.cookie_domain = ".example.com"
  • .htaccess: php_value session.cookie_domain .example.com
  • php script: ini_set('session.cookie_domain', '.example.com' );

(My web host does not allow modification of PHP via .htaccess so I tried the other 2 methods.)

However the session_regenerate_id(true); in my login.php conflicts with session.cookie_domain = ".example.com" in that after a header redirect, it empties the PHP session variable.

login.php

if (!isset($_SESSION)) { session_start(); }

// authentication codes...

session_regenerate_id(true);
$_SESSION['username'] = $username;
header('Location: redirect.php');
exit;

redirect.php

if (!isset($_SESSION)) { session_start(); }
var_dump($_SESSION); // returns array(0) { } if session.cookie_domain is set

I understand that using true in session_regenerate_id() would delete the old session, but it does not empty the session variable if session.cookie_domain is not set. Why is it so?

And the above 3 solutions do not work if I do not regenerate the session id, but doing so would result in session variable being emptied. Any idea how to solve this?

4

1 回答 1

1
<?php
session_start();
session_regenerate_id();
setcookie('session_id', session_id(), 0, '/', '.yourdomain.com');
if( !empty($_SESSION["user_logged_in"]) ){
header("Location: home.php");
} else {
header("Location: index.php");
}

显然setcookie安全性较低,但如果这三个都不适合您,这将帮助您,您可以使用原始域的附加会话,或者如果您想要额外的安全性以及 setcookie 选项甚至将它们存储在数据库中

于 2013-01-26T16:51:07.623 回答