Hello. Let's say I want to show a particular content to visitors only if they come from an array of websites (note: they may come from the subpages of those sites, so the appropriate regular expression match has to be used). $array = array('google.com','yahoo.com','bing.com'); // etc..., those are all whitelisted domains PHP: I need something like this: if(is_whitelisted()){ // show content } else{ // do nothing } PHP:
do as follows.. use $_SERVER['HTTP_REFERRER'] to determine referring url. Use parse_url() to parse the referrer url and get the domain name. Use in_array() to find the domain into your whitelist array. If found, display content, else do not display.
<?php $array = array('google.com','yahoo.com','bing.com'); // etc..., those are all whitelisted domains $referer = str_replace('www.', '', parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST)); if(in_array($referer, $array)){ // show content } else { // do nothing } ?> PHP:
Yeah, the above solution works, but it is not as effective for referrers with subdomains (e.g mail.yahoo.com or images.google.com). Can't I just check if any of the items in the array is contained in the referrer URL?
Subdomains will work, example: <?php $array = array('google.com','yahoo.com','bing.com'); // etc..., those are all whitelisted domains $referer = str_replace("www.", "", parse_url("http://images.google.com", PHP_URL_HOST)); if(in_array($referer, $array)){ //show content } else { // do nothing } ?> PHP: That would return false, since images.google.com aint within the array, if you want to also support subdomains you should clarify your description abit more.
Heres with subdomain support: <?php function parse_sub($url){ preg_match('@^(?:http://)?([^/]+)@i',$url, $matches); preg_match('/[^.]+\.[^.]+$/', $matches[1], $matches); return $matches[0]; } $array = array('google.com','yahoo.com','bing.com'); $referer = parse_sub($_SERVER['HTTP_REFERER']); if(in_array($referer, $array)){ //show content } else { //do nothing } ?> PHP: