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?