简体   繁体   中英

PHP Sessions from main and sub domains

I working with sessions in PHP and I wanted to know if you can pass sessions from one domain to another while using Ajax?

This is the index.html in domain.com

domain.com 
index.html -> jQuery
$.post($url,$form.serialize(),function(e){console.log(e)});

This is the index.php in sub.domain.com

sub.domain.com
json_encode<-index.php
==================== vvv INDEX.PHP PAGE vvv ======================
$session_options = array(
    'httponly' => true,
    'secure' => true,
    'domain' => 'domain.com'
);
session_set_cookie_params($session_options);
session_name( md5(sha1(md5($data))));
session_start();

switch ($_SERVER['HTTP_ORIGIN']){
    case 'www.domain.com':
            header('Access-Control-Allow-Origin: www.domain.com');
        break;
    case 'domain.com':
            header('Access-Control-Allow-Origin: domain.com');
        break;
}

header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header('Content-Type: application/json');

I am able to create a session in sub.domain.com if I visit it and if I go back to domain.com it crosses. However, when I call the sub.domain.com from domain.com it does not create the session and pass it to the domain.com. Or, should I do something like a JWT or Bearer Token?

Now, the reason why I am doing this is authentication, then after the authentication, the user can make other calls to other app functions.

So, trying my darndest, I have moved the ajax (sub.domain.com) to the same domain for debugging/testing. When I make the call using Ajax from the same domain (domain.com) it works and sets the PHP session cookie in the browser without navigating to the ajax folder (like physically opening the page). It will even go cross-domain to the sub-domains with no problems. But if I put the ajax back to the sub-domain, without physically opening the page, it will not set on an Ajax call.

After hours of research and then reverse engineering Google.com I found that google uses a datatype of Jsonp. After changing the dataType for my ajax request I get it to work cross-domain.

$.ajax({
    type: "GET",
    url: 'URL_GOES_HERE',
    data: form.serialize(),
    success: function(data, status, xhr){
        console.log(data);
        console.log(status);
        console.log(xhr.getAllResponseHeaders());
    },
    dataType: 'jsonp'
});

Now, the drawback to this is kind of heavy. jsonp can only work in a GET

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM