我就是这样做的。它会解析给定的 URL(如果有),然后删除所有不需要的信息,例如顶级域或三级或更低级域,因此我们只剩下二级域(google)。
function isRequestFromGoogle() {
if (!empty($_SERVER['HTTP_REFERER'])) {
$host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
if (!$host) {
return false; // no host found
}
// remove the TLD, like .com, .de etc.
$hostWithoutTld = mb_substr($_SERVER['HTTP_REFERER'], 0, mb_strrpos($_SERVER['HTTP_REFERER'], '.'));
// get only the second level domain name
// e.g. from news.google.de we already removed .de and now we remove news.
$domainName = mb_substr($hostWithoutTld, mb_strrpos($hostWithoutTld, '.') + 1);
if (mb_strtolower($domainName) == 'google') {
return true;
} else {
return false;
}
}
}