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.