Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How make PHP session work using subdomain and AJAX?

I'm working in a PHP project that uses subdomains, sessions and Ajax. But unfortunately I can't make it work! I'll try explain:

Let's assume that I'm at this domain: app.mysite.com/index.php

At this domain, I have a form that performs an Ajax request to mysite.com/functions/execute.php (without any subdomain)

In the first line of execute.php, I have a require_once that include a helper.php file. In this file I have put:

ini_set('session.cookie_domain',  '.mysite.com');
session_set_cookie_params(0, '/', '.mysite.com');
session_start();

All PHP files listed also include the helper.php.

If I for example run:

echo $_SESSION["myValue"];

At app.mysite.com/index.php or any other subdomain, like auth.mysite.com, I'll get the value: "test". But if I run the same code at execute.php, and return the value through Ajax I'll get undefined index!

What am I doing wrong?

like image 886
jNewbie Avatar asked Sep 28 '16 03:09

jNewbie


1 Answers

I already figure out how to make this work. Ajax Post method do not send credentials header by default, so we need to enable manually:

$.ajax({
    method   : "POST",
    url      : "https://example.com/functions/execute.php", 
    data     : myData,
    xhrFields: { 
        withCredentials: true
    }
}).done(function(result) {
    alert("success"));
});

And in execute.php you need to put:

ini_set('session.cookie_domain',  '.example.com');
session_set_cookie_params(0, '/', '.example.com');
session_start();
header('Access-Control-Allow-Credentials: true');

And if you request this from a subdomain, also need to put at example.php:

header('Access-Control-Allow-Origin: http://app.example.com');
like image 189
jNewbie Avatar answered Sep 29 '22 06:09

jNewbie