简体   繁体   中英

Loading certain page elements based on IP address

Couldn't quite find this exact question but I may have missed it. I was wondering whats the best way to load certain page elements based on the IP address of the site the visitor is coming from. In other words I only want to load a certain navigation button if the site visitor came from site X.

We are testing some cross-domain navigation on an e-commerce site and I want to provide a link that will get people back to their shopping cart if they navigate away from it to our main site. But I only want the link to show up if the people came from e-commerce site, hence I want to only load the link element if the referring IP address is a certain one.

I found the below code but I'm kind of a php newb so i don't know if this is the best way, or if there is a better way using javascript.

If ($_SERVER[“HTTP_REFERER”] == “ip address X”) 
{
               echo “<a href="http:// etc, etc"><div id=""> Back to shopping cart</div></a>”;
}

Thanks in advance

First: Note that the referer is NOT reliable. While in most cases it will show where a user came from, you should not DEPEND on it being accurate. Security/privacy software will tamper with the value or suppress it entirely.

That being said: the referer is just a url, so

$url = $_SERVER['HTTP_REFERER'];
$urlparts = parse_url($url); // decompose url into components

$host = $urlparts['host']; // get the hostname

$ip = gethostbyname($host); // do DNS lookup for hostname->ip

if ($ip == '127.0.0.1') {
   echo "Hey, you must be sitting next to me!"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM