سؤال

I have a example.com/login.php file on root domain with this code

header('Access-Control-Allow-Origin: *');
session_set_cookie_params(0, '/', '.example.com');
session_name('lusession');
session_start();
$_SESSION['name'] = $_GET['name'];
$_SESSION['useremail'] = $_GET['useremail'];
$_SESSION['password'] =  $_GET['password'];

This file is provided with credentials and it then creates login session. It is called from main domain and subdomains by AJAX.

The problem is it doesnot creat session when called through AJAX, but when opened directly in browser as querystring it creates cross domain session as expected.

Other pages which call it through AJAX have following code in them at start:

session_set_cookie_params(0, '/', '.example.com');
session_name('lusession');
session_start();

If I add following code in login.php it shows in AJAX response that session is created. But that session is not available on pages on same domain and on other subdomains.

echo 'session created for'.$_SESSION['name'];

Inspecting resource shows AJAX call creates session cookie with name 'lusession' as it should.

هل كانت مفيدة؟

المحلول 2

Well figured it out.

Actualy AJAX calls only send Cookies if the url you're calling is on the same domain as your calling script. Subdomains are considered seperate domains. Though this code creates cross subdomain sessions but AJAX involved is culprit.

As in this case I am trying to call a url from domain.com while my calling script is on sub.domain.com (In other words: I made a Cross Domain Call in which case the browser didn't sent any cookies to protect privacy).

The solution that worked for me is I put login.php file on every subdomain for calls from that subdomain. This way sessions were created, and once a session is created on one subdomain it is available on all subdomains as wanted.

نصائح أخرى

Access to the session cookie by scripting languages is controlled with the session.cookie_httponly configuration setting. Or you can use the 5th parameter of session_set_cookie_params() if you prefer this.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top