Recently a number of people have been discussing the idea of serving up Google adverts conditionally based on the referring site. By targeting referrals from search engines this gives them the opportunity to gain some extra revenue from what are likely one time visitors whilst keeping their sites advert free for regular visitors. To me this seems a sensible approach. I've written a quick function to facilitate this which detects if the user has visited the page from a search engine and returns true or false accordingly. To keep the regular expression line short I've only included Google and Yahoo but you can easily add others - just add them, pipe separated, between the rounded brackets in the regular expression.
<?phpfunction IsFromSearchEngine() {if (isset($_SERVER['HTTP_REFERER']) && preg_match("/^https?:\/\/[0-9a-z]*\.?(google|yahoo)\..+\/.*$/i", $_SERVER['HTTP_REFERER'])) {return true;}return false;}?>
To use simply include this function and wrap the following code around your Google advert calls.
<?phpif (IsFromSearchEngine()) {echo 'Adverts';}?>
Understanding The Regular Expression
The regular expression is fairly complete. There are more checks that could be made but I honestly don't think it's worth it for this problem.
- ^ - matches the start of the string.
- http - matches, well "http".
- s? - optionally matches a single letter "s" to cater for "http" and "https".
- : - matches a colon.
- \/\/ - matches two forward slashes. They need to be escaped with a backlash in the regular expression as they otherwise delimit the start and end of the expression.
- [0-9a-z]* - matches zero or more instances of the character ranges 0-9 and a-z.
- \.? - optionally matches a literal full stop (period).
- (google|yahoo) - matches the term "google" or the term "yahoo".
- \. - matches a literal full stop (period).
- .+ - matches one or more characters.
- \/ - matches a forward slash.
- .* - matches zero or more characters
- $ - matches the end of the string.
The "i" after the final forward slash is a modifier which makes the entire regular expression case insensitive.
Thanks, Ed!
Unless the advertising is something obtrusive and annoying I don't see why you'd remove it for regulars. Whenever I browse around I'm not annoyed by advertising unless it's doing something overly obtrusive to catch my attention. So IMO it seems like a waste of CPU cycles.
Also you're error log is going to be filled with uninitialized variable $_SERVER['HTTP_REFERER'] pretty quikcly. :)
Martin - well spotted, thanks. I've updated the code accordingly.