I often hear people say to use "$_SERVER['SERVER_ADDR']
", but that returns the LAN IP of my server (e.g. 192.168.1.100). I want the external IP.
In order to obtain the IP address of the server one can use ['SERVER_ADDR'], it returns the IP address of the server under the current script is executing. Another method is using the ['REMOTE_ADDR'] in the $_SERVER array.
The simplest way to collect the visitor IP address in PHP is the REMOTE_ADDR. Pass the 'REMOTE_ADDR' in PHP $_SERVER variable. It will return the IP address of the visitor who is currently viewing the webpage.
Here are the instructions for windows:Type cmd and press enter. In this new windows type ipconfig and press enter. You will see a bit more information than you may want what your looking for is IPv4 Address. The number across from that is your local IP address.
There is NO way to get your underlying IP Address that has been designated by your ISP via conventional PHP if you are using a router. A way to get the external IP is to find a service that will obtain it for you and echo the address back to you. I found a handy service which does just that. http://ipecho.net/
You can use:
$realIP = file_get_contents("http://ipecho.net/plain");
Just query a host that returns your IP address:
$externalContent = file_get_contents('http://checkip.dyndns.com/'); preg_match('/Current IP Address: \[?([:.0-9a-fA-F]+)\]?/', $externalContent, $m); $externalIp = $m[1];
or, set up a service that simply echoes just the IP, and use it like this:
$externalIp = file_get_contents('http://yourdomain.example/ip/');
Set up the service yourself by simply echoing the remote IP address, or pay someone to host it. Do not use somebody else's server without permission. Previously, this answer linked to a service of mine that's now being hit multiple times a second.
Note that in an IP network with one or more NATs, you may have multiple external IP addresses. This will give you just one of them.
Also, this solution of course depends on the remote host being available. However, since there is no widely implemented standard (no ISP and only some home routers implement UPnP), there is no other way to get your external IP address. Even if you could talk to your local NAT, you couldn't be sure that there isn't another NAT behind it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With