What are some common pitfalls when using PHP to extract keywords from a search engine referrer?
One common pitfall when extracting keywords from a search engine referrer in PHP is not properly handling different search engines' referral URLs. Each search engine may have a different format for passing keywords, so it's important to account for these variations. One way to solve this issue is to create a function that parses the referral URL based on the search engine and extracts the keywords accordingly.
function extractKeywordsFromReferrer($referrer) {
$keywords = '';
if (strpos($referrer, 'google') !== false) {
if (preg_match('/q=([^&]*)/', $referrer, $matches)) {
$keywords = urldecode($matches[1]);
}
} elseif (strpos($referrer, 'bing') !== false) {
if (preg_match('/q=([^&]*)/', $referrer, $matches)) {
$keywords = urldecode($matches[1]);
}
} elseif (strpos($referrer, 'yahoo') !== false) {
if (preg_match('/p=([^&]*)/', $referrer, $matches)) {
$keywords = urldecode($matches[1]);
}
}
return $keywords;
}
$referrer = $_SERVER['HTTP_REFERER'];
$keywords = extractKeywordsFromReferrer($referrer);
echo "Keywords from referrer: " . $keywords;