2

I need to get Public IP address of the system using PHP. I tried the following function:

function get_server_ip() { $ipaddress = ''; if(getenv('HTTP_X_FORWARDED_FOR')) $ipaddress = getenv('HTTP_X_FORWARDED_FOR'); else if(getenv('HTTP_X_FORWARDED')) $ipaddress = getenv('HTTP_X_FORWARDED'); else if(getenv('HTTP_FORWARDED_FOR')) $ipaddress = getenv('HTTP_FORWARDED_FOR'); else if(getenv('HTTP_FORWARDED')) $ipaddress = getenv('HTTP_FORWARDED'); else if(getenv('REMOTE_ADDR')) $ipaddress = getenv('REMOTE_ADDR'); return $ipaddress; } 

But, I got only the localhost IP 127.0.0.1. I am in need of the server's public IP address. What function is available in PHP to get my public IP address which I get from this site: http://www.whatismyip.com/

3
  • That is your ip address when testing locally Commented Apr 16, 2014 at 13:31
  • @JohnConde so, can't I get the global IP address ? Commented Apr 16, 2014 at 13:32
  • 4
    You will get the IP that made the request. If you do a request locally 127.0.0.1 is your IP. If you can route the traffic outside of local network somehow you will see an external IP. Commented Apr 16, 2014 at 13:35

1 Answer 1

14

It is not possible to get Your IP address on that way if you run web server on same machine or local LAN where you run your browser client, you will always get local IP address.

If You still want to get Your public address from PHP script, on *nix servers which runs in same network as your browser client, you can get it via command like this:

$myPublicIP = trim(shell_exec("dig +short myip.opendns.com @resolver1.opendns.com")); echo "My public IP: ".$myPublicIP; 
Sign up to request clarification or add additional context in comments.

1 Comment

This works 100% thank you. My PC is running XAMPP on Ubuntu 20.04 X64

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.