View Full Version : Handling many sub-domains

07-30-2007, 11:45 AM

I have a site which has many sub-domains. Accessing each of them should lead to a simple page, saying:
"hello, ".$subdomain, where $subdomain is the current sub domain in the address bar.

Can it be done using only 1 file, or I must put in each and every sub-domain a different HTML file with different text?


07-30-2007, 01:20 PM
Unless you directed each sub domain to the same document root folder, which would defeat the point. If not then you would need a separate file in each of the sub domains document root.

I have seen one website that does this. If you didnt bother setting up any virtual hosts for the other domains then you could technically put any subdomain in to the address bar you wanted and it will still direct to the same page.

For instance if you had a site called http://isanoob.com and you wanted this page to display "{subdomain} is a noob"

so submitting timmy.isanoob.com would submit timmy "is a noob"

If this is the kind of thing you are thinking of then you could achieve this with file. In fact you page directs for the sub domoain wouldn't actually be directed anywhere other than the document root of the main domain. All you would have to do is remove the subdomain part of the page query. This can be done easily with $_SERVER['HTTP_HOST'];

function get_subdomain() {
// Explode the HOST into it's constituent parts:
$parts = explode('.', $_SERVER['HTTP_HOST']);
$cp = count($parts);

// If a 1 part hostname like 'localhost' don't bother with a subdomain:
if ($cp == 1) { $subdomain = ''; }
// Otherwise, generate our subdomain by using the last 2 parts
else { $subdomain = ".{$parts[$cp-2]}.{$parts[$cp-1]}"; }

return $subdomain;

echo $subdomain.' is a noob';