2013-03-28 42 views
1

我正在構建一個應用程序,它使用位於數據庫中的用戶的子域和自定義域名,因此如果請求來自另一個域,我會從數據庫中檢查該自定義url是否確實存在,或者當請求來自子域時,我會檢查它是否存在。如果是我做我的東西。檢測請求是否來自不同域或子域的最佳方法

考慮這一點我一個簡單的例子,我在尋找:

if(is_user_request()) 
{ 
    $url = get_url(); 
    // assuming that get_url() magically decides whether to output .. 
    // a custom domain (http://domain.tld) 
    // or a subdomain's first part (eg. "this".domain.tld) 
} 
else 
{ 
    // otherwise it's not a sub domain nor a custom domain, 
    // so we're dealing with our own main site. 
} 

現在你繼續假設,因爲我有0代表,我在這裏要求「德守則」之前。我這樣做,這是下面的工作完全辦法:

// hosts 
$hosts = explode('.', $_SERVER['HTTP_HOST']); 

// if there is a subdomain and that's under our $sitename 
if(!empty($hosts[1]) AND $hosts[1] === Config::get('domain_mid_name')) 
{ 
    $url = $hosts[0]; 
    $url_custom = false; 
} 

// if there is no subdomain, but the domain is our $sitename 
elseif(!empty($hosts[0]) AND $hosts[0] === Config::get('domain_mid_name') AND !empty($hosts[1]) AND $hosts[1] !== Config::get('domain_mid_name')) 
    { 
    $url = false; 
    $url_custom = false; 
} 

// otherwise it's most likely that the request 
// came from a entirely different domain name. 
// which means it's probably $custom_site 
else 
{ 
    $url = false; 
    $url_custom = implode('.', $hosts); 
} 

if($url) 
{ 
    return $url; 
} 

if($url_custom) 
{ 
    return $url_custom; 
} 

不過,我敢肯定有更好的這樣做的方式。因爲首先,HTTP_HOST不包含'http://',所以我需要手動添加,而且我非常確定整個if,else事情只是一個矯枉過正的問題。所以,比我聰明的人,請賜教。

哦,不,我沒有預先定義的子域。我有一個簡單的通配符* .domain.tld設置,所以所有子域都轉到主腳本。我只是這樣說,因爲從我尋找解決方案的過程中,我發現了許多答案,建議手動創建一個子域,它甚至與我所要求的甚至沒有遠程相關,所以讓我們跳過這個主題。

回答

1

如前所述,$_SERVER['HTTP_HOST']是要走的路。

但是在你的代碼中有錯誤。您假定發送的主機名由2個或3個組件組成,但您無法確定。你至少應該檢查count($hosts)

例如,如果您使用domain.tld作爲您自己的網站,那麼您最好先查看是否發送了domain.tld(您快速返回您的網頁);然後查看substr($_SERVER['HTTP_HOST']...,-11)==='.domain.tld',如果是,返回子網站(與任何級別的子域一起工作,仍然快);其他錯誤恢復,因爲一個完全的外部域已經路由到你。關鍵要注意的是,層次結構的頂級域匹配意味着匹配右對齊的主機名字符串:

 .domain.tld | subsite-pattern 
    sub12.domain.tld | MATCH 
    sub12.dumain.tld | NO MATCH 
    sub12domain.tld | NO MATCH 
+0

這是一個更好的答案。關於速度的注意也非常感謝。 –

2

$_SERVER['HTTP_HOST']是這樣做的正確方法,除非您想將不同的參數從Web服務器傳遞到PHP。

至於協議,請注意請求協議應該由$_SERVER['HTTPS']決定,而不是假設它是http

用於提取子域,你可以看看使用array_shift,然後運行

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

但通常你有什麼是應該做。