Reputation: 15106
According to Allow php sessions to carry over to subdomains, there are 3 ways to allow PHP sessions across different subdomains.
session.cookie_domain = ".example.com"
php_value session.cookie_domain .example.com
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?
Upvotes: 1
Views: 256
Reputation: 4204
<?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");
}
Obviously setcookie
is less secure, but if all three do not work for you that will help you out, you can use an additional session of the original domain or even store them in database if you want additional securuty along with setcookie option
Upvotes: 1