0

Problem

I have a page which is generated entirely through JavaScript. I grab the content by requesting data from a PHP script on a subdomain (ajx.example.com), then return it in JSON format.

One of the requirements for this particular page is to be "editable" if a user is logged in (which is one of the keys in the JSON, "isEditable":true). If I visit the request page (on the subdomain) directly, and the user is logged in on (on the main domain), isEditable is always true. However, if I request it via an Ajax request, it's always false.

These subdomains are done through a VirtualHost on MAMP, and all point to the same directory.
www.example.com is in htdocs/example,
ajx.example.com is in htdocs/example/ajax, and
v1.examplecdn.com is in htdocs/example/cdn.


Code

Here is the init page (www.example.com/app/init.php:

ini_set("session.cookie_domain", ".example.com"); // make sure all sessions are available on all subdomains
error_reporting(E_ALL);
session_start();

// I include the user class here

Here is the request page (ajx.example.com/request.php):

require_once "../app/init.php"; // (/htdocs/example/app/init.php)
header("Content-type: application/json;charset=utf-8", false);
header("Access-Control-Allow-Origin: http://www.example.com", false);

$user = new User();
$editable = false;

if($user->loggedIn()){ // check if user is logged in (this is stored in a session on .example.com
    $editable = true;
}
die(json_encode(array("isEditable" => $editable)));

And here is the request Ajax (v1.examplecdn.com/request.js):

var container = document.getElementById("container");
ajax({
    url: "//ajx.example.com/request.php", // (/htdocs/example/ajax/request.php)
    dataType: "json",
    success: function(res){
        if(res.isEditable){
            console.log("editable"); // this doesn't come through as isEditable is false.
        }
    }
}); 

Request

If anyone can point me into the direction of how to make it so that those PHP Sessions can be accessed via those subdomains, it would be greatly appreciated!
Cheers.

GROVER.
  • 4,071
  • 2
  • 19
  • 66

1 Answers1

0

You are right until this setting - ini_set("session.cookie_domain", ".example.com"); // make sure all sessions are available on all subdomains

But as you have different domains on different VM's, they cannot share the session, as each of the VM will create its own copy of new session, to allow session sharing you need to save sessions either in DB or in cache service , like memcache, redis etc.

saving sessions in db table has been explained here

How do I save session data to a database instead of in the file system?

Gaurav Garg
  • 137
  • 1
  • 9
  • 1
    I don’t know where you are getting “different VM's” from, the question only mentioned VirtualHosts. – CBroe Jun 12 '18 at 06:45