datasn.io
datasn.io

Reputation: 12867

What's the best way to identify subdomains by PHP dynamically?

I have configured the wildcard DNS of *.mydomain.com and it's all working properly. My question is which of these should I rely on identifying client subdomain requests?

  1. $_SERVER["HTTP_HOST"]
  2. $_SERVER["SERVER_NAME"]
  3. $_SERVER["SCRIPT_URI"]

They all seem to contain the subdomain part I want but after reading this article by Chris: http://shiflett.org/blog/2006/mar/server-name-versus-http-host, I'm lost at sea and there appears to be no safe way to do this?

Any idea on accomplishing this task securely? Which approach would you prefer?

Update: sorry, I meant this post: http://shiflett.org/blog/2006/mar/server-name-versus-http-host

Upvotes: 1

Views: 348

Answers (5)

Your Common Sense
Your Common Sense

Reputation: 157828

Too much talk of such a little problem.
Everyone says its dangerous but noone bother to write a solution, as simple as

$mydomain='example.com';
$subdomain="";
$matches=array();

$pat='!([a-z0-9_]+)\.'.preg_quote($mydomain).'$!i';
if (preg_match($pat,$_SERVER['HTTP_HOST'],$matches)) $subdomain=$matches[1];

Upvotes: 0

Rasmus
Rasmus

Reputation: 451

HTTP_HOST comes directly from the HOST header. Apache does not clean it up in any way. Even for non-wildcard setups, your first virtualhost in your config will receive a request for a HOST header that doesn't match any of your configured vhosts, so you have to be careful with it. Treat it like any other user data. Filter it appropriately before using it.

Upvotes: 3

zaf
zaf

Reputation: 23244

You can use any but most use HTTP_HOST.

You don't have to worry about 'security' here since you allow a wildcard for your subdomains. You won't be able to stop a user from entering a 'threatening' subdomain and sending a request to your server.

If you want to disallow certain subdomains then you have several options but thats a different question.

Upvotes: 0

Mark Tomlin
Mark Tomlin

Reputation: 8923

$subdomain = explode('.', $_SERVER['HTTP_HOST'], -2);

Returns an array always, and can be empty if there is no sub domain. You should also make sure to notice that this could return www as an array value and that would link to your root domain anyway.

Upvotes: 0

sjobe
sjobe

Reputation: 2837

I'd suggest that you get the current page url, then use a regular expression to check. Be sure to ignore things link www, www2, etc.

Upvotes: 1

Related Questions