Antony
Antony

Reputation: 15106

Why is $_SESSION emptied?

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

(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

Answers (1)

Patt Mehta
Patt Mehta

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

Related Questions