开发者

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

I h开发者_如何学Cave 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


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.


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.


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.


$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.


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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜