How can I find with p h p if someone comes to my website from google?
<?php
if (isset($_COOKIE['source'])) {
$arr = explode("=",$_COOKIE['source']);
$_SESSION['source'] = $arr[1];
unset($_COOKIE['source']);
}
?>
This is how I get the source, to know where was the visitor before my site and I want to set $_SESSION['source']="google"
if he was searching on Google to find my page.
if(strpos($_SERVER['HTTP_REFERER'], 'google'))
echo 'comes from google';
Try checking $_SERVER['HTTP_REFERER']. This global variable should contain the referer url.
This is how I would do it. It parses the given URL if there is any and then removes all unneeded information like Top-Level-Domain or third- or lower level domains, so we only have the second level domain remaining (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;
}
}
}