My IP is showing up wrong in PHP home server

2019-07-16 15:54发布

问题:

Ok simple enough

<?PHP
echo $_SERVER[REMOTE_ADDR];
?>

Ok maybe not, I my IP is currently 72.184.212.85 however the code above which I am using on an IP blocking system for a script shows my IP as my home server IP of 127.0.0.1

So when I go to my script my IP is shown as 127.0.0.1 but when I go to other websites it is shown as 72.184.212.85

How can I get the first value to show on my test server?

回答1:

$_SERVER['REMOTE_ADDR'] will always show the IP address from which the request came. If you access your own script on your own computer within your own network, your external IP address never comes into play. The request would have to leave your local network and then come back in for the external address to show up, but if it's all local, that'll never happen.



回答2:

You'll have to make your server publicly accessible and then access it from the public address. I'm guessing you're currently using localhost to access your server?

run your server say port 8080 and then forward the port in your router so it's public to the internet. Then visit your webpage/phpscript from http://72.184.212.85:8080 instead of http://localhost:8080.



回答3:

Here is a ridiculous solution that I wouldn't recommend:

Register your home IP with a domain name, then see where the request came from via URL:

$url = $_SERVER["SERVER_NAME"];

or

$url = $_SERVER["HTTP_HOST"];

and then do a dns lookup of that result, which should return the IP it's registered to, ie your external IP.

 $ext_ip = gethostbyaddr($url);

The only reason this wouldn't work (so sorry if I'm wrong), is if SERVER_NAME uses the same method as "REMOTE_HOST", which is a reverse DNS lookup, which won't resolve, as your internal IP won't be registered to that domain name. An easy way to check is to do either:

 phpinfo();

and see what the environmental variables are.



标签: php ip