-1

I have a login page which exist in my main domain. I want to set session some specific subdomain.

Suppose My login page is example.com After successfully login my page will go to cms.example.com or admin.example.com. Session should store this three example.com, cms.example.com and admin.example.com not other subdomain.

Currently I got session only my example.com but I am unable to get any session in above 2 subdomain.

I found some related question and answer here Allow php sessions to carry over to subdomains | Set session cookies for specific subdomains but this is set for all domains. Here is problem because I have some other subdomains like user.example.com, studio.example.com, demo.example.com etc.

How to set session for specific domain and subdomain?

Developer
  • 2,676
  • 8
  • 43
  • 65

2 Answers2

0

Sessions can't travel to sub domains. If you want to send a session to 2 different sub domains and not to the rest I'd recommend using cookies and set them to a specific folder containing the subdomain. If that is not what you are looking for you can set it for all sub domains:

ini_set('session.cookie_domain', substr($_SERVER['SERVER_NAME'], strpos($_SERVER['SERVER_NAME'],"."), 100));
RageMasterGaming
  • 77
  • 1
  • 1
  • 4
0

I am assuming you've already included a file that takes the domain and lops off the sub domain.
I had the similar issue. I solved it by this trick.

Method 1:

Add a prefix before your sessions distinguishing session for your sub domains. For Example: $_Session["cms.id"], $_Session["admin.id"]

Method 2:

Create a class for sessions with attributes domain and rest of the information you want to store.

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;
}

}

Now you can create CustomSession object and set $domain with the domain you want that session to be used in.

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

You can then check in your sub-domains the value of $domain and carry your logic accordingly.

if($obj->getDomain()=='cms.example.com'){
// your code goes here
}
Javapocalypse
  • 2,223
  • 17
  • 23
  • I am not asking about Distributing session `$_Session["id"]` should work in `example.com`, `cms.example.com` and `admin.example.com` because my all three file code is one. pointed also one directory. – Developer Dec 13 '17 at 10:42