Separating Subdomain from Domain and TLD

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Separating Subdomain from Domain and TLD

Post by tr0gd0rr »

I'm trying to set up sessions to work across subdomains. It is simple to use ini_set('session.cookie_domain', "$domain.$tld") when you know the domain. And here is the code I'm using to take care of it dynamically:

Code: Select all

if (preg_match('/[^\.]+\.[a-z]{2,6}$/i', $_SERVER['HTTP_HOST'], $match)) { 
  // set cookie to work across all subdomains
  ini_set('session.cookie_domain', '.' . $match[0]);
} 
But what if I need the code to detect multi-part top-level domains? For instance, I'm hoping to have the following results:
"domain.com" : set ini to ".domain.com"
"sub.domain.com" : set ini to ".domain.com"
"sub.sub.domain.com" : set ini to ".domain.com"
"domain.ca.us.gov" : set ini to ".domain.ca.us.gov"
"sub.domain.ca.us.gov" : set ini to ".domain.ca.us.gov"
"localhost" : do not set ini

It seems like Apache would know the difference between subdomain, domain and TLD. Does it? And if so, how can I find out from php?
spider.nick
Forum Commoner
Posts: 72
Joined: Wed Jul 15, 2009 12:22 pm
Location: Overland Park, KS

Re: Separating Subdomain from Domain and TLD

Post by spider.nick »

domain.ca.us.gov is not a TLD. The TLD in that sub-domain is .gov.

Nick
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Re: Separating Subdomain from Domain and TLD

Post by tr0gd0rr »

ah. I didn't realize that.

In the situation of "domain.ca.us.gov" my code above would set the session domain to ".us.gov". Would that set a cookie across all ".us.gov" domains? What about country domains such as ".co.uk". Would it work to set the session domain to ".co.uk"?
spider.nick
Forum Commoner
Posts: 72
Joined: Wed Jul 15, 2009 12:22 pm
Location: Overland Park, KS

Re: Separating Subdomain from Domain and TLD

Post by spider.nick »

tr0gd0rr wrote:ah. I didn't realize that.

In the situation of "domain.ca.us.gov" my code above would set the session domain to ".us.gov". Would that set a cookie across all ".us.gov" domains? What about country domains such as ".co.uk". Would it work to set the session domain to ".co.uk"?
If I am thinking clearly, .co.uk is a TLD. So, no. <site_name>.co.uk would be the domain.

Nick
Post Reply