【问题标题】:passing php sessions from subdomains working on subdomain but not ajax request从处理子域但不处理ajax请求的子域传递php会话
【发布时间】:2018-11-21 10:38:59
【问题描述】:

问题

我有一个完全通过JavaScript生成的页面。我通过从子域(ajx.example.com))上的 PHP 脚本请求数据来获取内容,然后以 JSON 格式返回。

如果用户登录,则此特定页面的要求之一是“可编辑”(这是 JSON 中的键之一,"isEditable":true)。如果我直接访问请求页面(在子域上),并且用户登录(在主域上),isEditablealways true。但是,如果我通过 Ajax 请求请求它,它始终是 false

这些子域是通过 MAMP 上的 VirtualHost 完成的,并且都指向同一个目录。
www.example.comhtdocs/example 中,
ajx.example.comhtdocs/example/ajax 中,
v1.examplecdn.comhtdocs/example/cdn 中。


代码

这里是 init 页面(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

这是请求页面 (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)));

这里是请求 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.
        }
    }
}); 

请求

如果有人能指出如何制作它以便可以通过这些子域访问那些 PHP 会话,那将非常感谢
干杯。

【问题讨论】:

  • 您的ajax 函数在哪里设置了通过跨域请求传递cookie 所需的参数?
  • @CBroe 老实说,我不知道这是一个要求。我该怎么做? :)

标签: javascript php ajax apache


【解决方案1】:

在这个设置之前你是对的 - ini_set("session.cookie_domain", ".example.com"); // 确保所有会话在所有子域上都可用

但是由于您在不同的虚拟机上有不同的域,它们无法共享会话,因为每个虚拟机都会创建自己的新会话副本,以允许会话共享,您需要将会话保存在数据库或缓存服务中,比如memcache、redis等

这里已经解释了如何在 db 表中保存会话

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

【讨论】:

  • 我不知道你从哪里得到“不同的虚拟机”,这个问题只提到了 VirtualHosts。
猜你喜欢
  • 2012-01-17
  • 1970-01-01
  • 2015-01-14
  • 2022-07-22
  • 1970-01-01
  • 2013-06-04
  • 2011-03-02
  • 2018-11-29
  • 1970-01-01
相关资源
最近更新 更多