透過分析 $_SERVER['HTTP_REFERER'],可識別訪客來自哪個搜尋引擎並提取搜尋關鍵字。本文提供完整的類別實作,支援主流中文搜尋引擎。
<?php
class KeywordExtractor {
public function getKeyword($referer) {
if (strpos($referer, 'https://www.baidu.com') !== false) {
return $this->getBaiduKeyword($referer);
} elseif (strpos($referer, 'https://www.google.com') !== false) {
return $this->getGoogleKeyword($referer);
} elseif (strpos($referer, 'https://www.soso.com') !== false) {
return $this->getSosoKeyword($referer);
} elseif (strpos($referer, 'https://www.sogou.com') !== false) {
return $this->getSogouKeyword($referer);
}
return '';
}
private function getBaiduKeyword($str) {
return $this->extractParam($str, 'wd=');
}
private function getGoogleKeyword($str) {
return $this->extractParam($str, 'q=');
}
private function getSosoKeyword($str) {
// SOSO 可能用 w= 或 &w=
$kw = $this->extractParam($str, 'w=');
if (!$kw) $kw = $this->extractParam($str, '&w=');
return $kw;
}
private function getSogouKeyword($str) {
return $this->extractParam($str, 'query=');
}
private function extractParam($url, $param) {
$pos = strpos($url, $param);
if ($pos === false) return '';
$str = substr($url, $pos + strlen($param));
$end = strpos($str, '&');
if ($end !== false) $str = substr($str, 0, $end);
return rawurldecode($str);
}
}
// 使用範例
$extractor = new KeywordExtractor();
$keyword = $extractor->getKeyword($_SERVER['HTTP_REFERER'] ?? '');
echo "搜尋關鍵字:$keyword";
?>
wd、Google q、SOSO w、搜狗 query。urlencode,必須用 rawurldecode() 還原(注意空格會被編碼為 + 或 %20,rawurldecode 會將 + 保留為 +,若需轉空格請自行 str_replace('+', ' ', $kw))。q=)、360搜尋 (q=)、Yandex (text=) 等。parse_url() + parse_str() 系統化解析查詢字串,比手動 strpos/substr 更健壯。