應用場景
- 📊 站內搜索熱詞統計與推薦
- 🎯 根據關鍵詞動態調整頁面內容/廣告
- 🔍 SEO 效果監測:哪些詞帶來了流量
核心實現:解析 HTTP_REFERER
<?php
/**
* 從 HTTP_REFERER 解析搜索引擎關鍵詞
* @return array ['keyword' => string, 'from' => string]
*/
function search_word_from() {
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$keyword = '';
$from = '';
if (strstr($referer, 'baidu.com')) {
// 百度:wd 或 word 參數
preg_match("|baidu.+wd=([^&]*)|is", $referer, $tmp);
$keyword = urldecode($tmp[1] ?? '');
$from = 'baidu';
} elseif (strstr($referer, 'google.com') || strstr($referer, 'google.cn')) {
// Google:q 參數
preg_match("|google.+q=([^&]*)|is", $referer, $tmp);
$keyword = urldecode($tmp[1] ?? '');
$from = 'google';
} elseif (strstr($referer, 'so.com')) {
// 360 搜索:q 參數
preg_match("|so.+q=([^&]*)|is", $referer, $tmp);
$keyword = urldecode($tmp[1] ?? '');
$from = '360';
} elseif (strstr($referer, 'sogou.com')) {
// 搜狗:query 參數
preg_match("|sogou.com.+query=([^&]*)|is", $referer, $tmp);
$keyword = urldecode($tmp[1] ?? '');
$from = 'sogou';
} elseif (strstr($referer, 'soso.com')) {
// 搜搜:w 參數
preg_match("|soso.com.+w=([^&]*)|is", $referer, $tmp);
$keyword = urldecode($tmp[1] ?? '');
$from = 'soso';
}
return ['keyword' => $keyword, 'from' => $from];
}
// 測試用法
$word = search_word_from();
if (!empty($word['keyword'])) {
echo '關鍵字:' . $word['keyword'] . ' 來自:' . $word['from'];
}
注意事項與局限
- HTTPS 引用策略:現代瀏覽器在 HTTPS → HTTP 跳轉時會隱藏 Referer,導致無法獲取關鍵詞。
- 搜索引擎加密搜索:Google、百度等已全面啟用 HTTPS 加密搜索,Referer 中往往不再攜帶關鍵詞參數。
- 替代方案:對接搜索引擎站長平台 API(如百度搜索資源平台、Google Search Console)獲取完整搜索詞報表。
擴展建議
- 增加對
sm.cn(神馬)、duckduckgo.com 等引擎的支持。
- 結合
utm_source 等 UTM 參數做更精準的流量歸因。
- 將解析結果寫入 Redis/MySQL,構建關鍵詞熱度排行榜。