【问题标题】:How to set session for specific subdomain in PHP?如何在 PHP 中为特定子域设置会话?
【发布时间】:2018-05-27 00:18:36
【问题描述】:

我的主域中有一个登录页面。我想设置会话一些特定的子域。

假设我的登录页面是example.com 成功登录后我的页面将转到cms.example.comadmin.example.com。会话应该存储这三个example.comcms.example.comadmin.example.com 而不是其他子域。

目前我只获得了我的example.com 会话,但我无法在以上 2 个子域中获得任何会话。

我在这里找到了一些相关的问题和答案Allow php sessions to carry over to subdomains | Set session cookies for specific subdomains 但这是为所有域设置的。这是问题,因为我还有一些其他子域,例如 user.example.comstudio.example.comdemo.example.com 等。

如何为特定域和子域设置会话?

【问题讨论】:

  • 独立服务器?您是否将会话数据存储在共享数据库中?
  • @LawrenceCherone 不,我存储在同一台服务器上

标签: php apache .htaccess session cookies


【解决方案1】:

会话不能传送到子域。如果您想将会话发送到 2 个不同的子域而不是其他子域,我建议您使用 cookie 并将它们设置为包含子域的特定文件夹。如果这不是您要查找的内容,您可以为所有子域设置它:

ini_set('session.cookie_domain', substr($_SERVER['SERVER_NAME'], strpos($_SERVER['SERVER_NAME'],"."), 100));

【讨论】:

    【解决方案2】:

    我假设您已经包含了一个 takes the domain and lops off the sub domain. 的文件
    我有类似的问题。我用这个技巧解决了它。

    方法一:

    在您的会话之前添加一个前缀,以区分您的子域的会话。 例如:$_Session["cms.id"], $_Session["admin.id"]

    方法二:

    为具有 domain 属性和您要存储的其余信息的会话创建一个类。

    class CustomSessions{
    private $domain;
    private $userId;
    
    /**
     * @return mixed
     */
    public function getDomain()
    {
        return $this->domain;
    }
    
    /**
     * @param mixed $domain
     */
    public function setDomain($domain)
    {
        $this->domain = $domain;
    }
    
    /**
     * @return mixed
     */
    public function getUserId()
    {
        return $this->userId;
    }
    
    /**
     * @param mixed $userId
     */
    public function setUserId($userId)
    {
        $this->userId = $userId;
    }
    
    }
    

    现在您可以创建 CustomSession 对象并将 $domain 设置为您希望在其中使用该会话的域。

    $obj = new CustomSession();
    $obj->setDomain("cms.example.com");
    

    然后您可以在您的子域中检查 $domain 的值并相应地执行您的逻辑。

    if($obj->getDomain()=='cms.example.com'){
    // your code goes here
    }
    

    【讨论】:

    • 我不是在询问分发会话$_Session["id"] 应该在example.comcms.example.comadmin.example.com 中工作,因为我的所有三个文件代码都是一个。还指出了一个目录。
    猜你喜欢
    • 2011-12-23
    • 1970-01-01
    • 2021-12-01
    • 2017-02-07
    • 1970-01-01
    • 2011-09-21
    • 2017-10-20
    • 1970-01-01
    • 2014-09-04
    相关资源
    最近更新 更多