これが私がやる方法です。指定されたURLがある場合はそれを解析し、トップレベルドメインや第3レベル以下のドメインなどの不要な情報をすべて削除するため、セカンドレベルドメインのみが残ります(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;
}
}
}