用戶從搜索引擎點擊進入網站時,HTTP Referer 頭通常包含搜索關鍵詞參數。解析 Referer URL 的查詢字符串即可提取關鍵詞與來源。
<?php
function search_word_from() {
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$keyword = '';
$from = '';
if (strpos($referer, 'baidu.com') !== false) { // 百度
preg_match("|baidu.+wo?r?d=([^&]*)|is", $referer, $tmp);
$keyword = urldecode($tmp[1]);
$from = 'baidu';
} elseif (strpos($referer, 'google.com') !== false || strpos($referer, 'google.cn') !== false) { // Google
preg_match("|google.+q=([^&]*)|is", $referer, $tmp);
$keyword = urldecode($tmp[1]);
$from = 'google';
} elseif (strpos($referer, 'so.com') !== false) { // 360搜索
preg_match("|so.+q=([^&]*)|is", $referer, $tmp);
$keyword = urldecode($tmp[1]);
$from = '360';
} elseif (strpos($referer, 'sogou.com') !== false) { // 搜狗
preg_match("|sogou.com.+query=([^&]*)|is", $referer, $tmp);
$keyword = urldecode($tmp[1]);
$from = 'sogou';
} elseif (strpos($referer, 'soso.com') !== false) { // 搜搜
preg_match("|soso.com.+w=([^&]*)|is", $referer, $tmp);
$keyword = urldecode($tmp[1]);
$from = 'soso';
}
return array('keyword' => $keyword, 'from' => $from);
}
// 測試
$word = search_word_from();
if (!empty($word['keyword'])) {
echo '關鍵字:' . $word['keyword'] . ' 來自:' . $word['from'];
}
?>
| 挑戰 | 影響 | 應對策略 |
|---|---|---|
| HTTPS 全站普及 | Referer 不傳遞或僅傳遞源(Referrer-Policy: strict-origin-when-cross-origin) | 1. 設置 <meta name="referrer" content="no-referrer-when-downgrade"> 2. 依賴搜索引擎站長平台(百度統計、Google Search Console)獲取關鍵詞數據 |
| 隱私保護模式 | 瀏覽器/插件剝離查詢參數 | 無法完全解決,引導用戶使用站內搜索 |
| APP 內瀏覽器 | Referer 可能為空或非標準 | 在落地頁 URL 帶上 UTM 參數追蹤 |
parse_url() + parse_str() 替代正則,更健壯。htmlspecialchars 輸出轉義,防 XSS。