Pascal Bayer
Pascal Bayer

Reputation: 2613

JavaScript redirection problem with PHP sessions

I set a session variable on login subdomain, and response json from another subdomain if the login was successful, the responsed json is checked by a script and the script does a location.href = "new url". On the redirected site "new url" I want to check my session variables if the user is logged in or not, but there are no session variables set. Does location.href = "" destroy my session? How to fix this problem? session.cookie_domain is set to '.mydomain.com'.

login.mydomain.com:

$.post('http://api.mydomain.com/index.php', {action: 'login', username: username, password: password}, function(response) {
            var success = $.parseJSON(response);
            if(success.success == 'true') {
                location.replace = 'http://my.mydomain.com';
            }
        });

api.mydomain.com:

session_start();
$_SESSION['active'] = true;
header('Access-Control-Allow-Origin: http://login.mydomain.com');
echo '{"success": "true"}';

my.mydomain.com:

session_start();
if(!isset($_SESSION['active']) && !$_SESSION['active']) {
    header("Location: http://login.mydomain.com");
    echo $_SESSION['access_token'].' test';
}
else {   
    echo 'Success!'; 
}

Upvotes: 1

Views: 3500

Answers (3)

Ryan
Ryan

Reputation: 1888

From what you're saying you could have a couple of issues contributing to this problem.

  1. PHP cookies are set by the server when the page is loaded, no page load means no cookie is set, if you're using pure JSON with no page load then you may not be able to set your session and return it to the browser.

  2. Also remember that PHP sessions are effectively a cookie and the rules for cookies apply, so if you're setting a PHP session at api.mydomain.com and expect it to work at my.mydomain.com it probably wont work.

You can find a viable solution to handling login data and the sessions over multiple sub-domains here

Upvotes: 0

Isaac Chargoy Vivaldo
Isaac Chargoy Vivaldo

Reputation: 21

I had the same problem and I found when I use a relative url (location.ref="index.php"), all sessions variables exists. But when I use a absolute url (location.ref="http://mydomain.com/index.php") it kills all my session variables.

Upvotes: 2

shanethehat
shanethehat

Reputation: 15570

You don't seem to be calling session_start() in the second code block.

Upvotes: 1

Related Questions