Reputation: 901
Script from http://run.<EXAMPLE>.net/weblogin.php
<?php
switch ($_SERVER['HTTP_ORIGIN']) {
case 'http://www.<EXAMPLE>.net': case 'http://forums.<EXAMPLE>.net': case 'http://play.<EXAMPLE>.net':
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
break;
}
session_start();
$_SESSION['id'] = 5;
die($_SESSION['id']);
?>
AJAX call from http://www.<EXAMPLE>.net/index.php
$("#loginform").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "http://run.<EXAMPLE>.net/weblogin.php",
crossDomain: true,
data: {user: $("#userinput").val(), pass: $("#passinput").val()},
dataType: "text",
success: function(result) {
console.log(result);
}
error: function() {
alert("AJAX Error");
}
});
});
On my webpage I use the above AJAX to send data to the weblogin.php script, which in this simple example just sets and echos back the session variable id. The problem is that I can see on the server that this scripts creates a new session with an unfamiliar session id everytime it runs, instead of accessing the session id from the client's cookie.
All my other scripts work perfectly for retrieving a setting the session variables for the session with the id corresponding to the cookie including sessions over different subdomains, but not this AJAX. Is it something to do with CORS or the fact that I'm doing an AJAX? Do I have to manually get the correct id from the cookie and use that to identify the correct session?
Another strange thing is that I log the returned text from the AJAX in the console, but the result is blank even though the script should just echo the variable it just set to 5.
Edit So the weblogin.php script can't even grab cookies, it's almost like the AJAX isn't coming from my browser. If I run weblogin.php completely separate from the page or AJAX it works fine, it's just when doing a cross-subdomain AJAX that I can't access sessions or cookies and it creates a new session every time.
Upvotes: 0
Views: 1835
Reputation: 901
So I basically solved this by generating the session IDs myself and setting a cookie for them in the browser, assigning this cookie to a javascript variable with in-line PHP, then sending the cookie with the other data in the AJAX which the php script could then use with session_id() to resume the correct session.
I'm not completely sure about the security implications of this, but I figure it's pretty much the same thing as sending the cookie in the header and just accessing it through $_COOKIE.
Upvotes: 1
Reputation: 2414
Be sure that for your AJAX file you have set up the same domain for cookies and you have
session_start()
in your code before you use session data. This should help. If not - simply show me your AJAX file.
Upvotes: 0