我正在構建一個應用程序,它使用位於數據庫中的用戶的子域和自定義域名,因此如果請求來自另一個域,我會從數據庫中檢查該自定義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設置,所以所有子域都轉到主腳本。我只是這樣說,因爲從我尋找解決方案的過程中,我發現了許多答案,建議手動創建一個子域,它甚至與我所要求的甚至沒有遠程相關,所以讓我們跳過這個主題。
這是一個更好的答案。關於速度的注意也非常感謝。 –