This question already has an answer here:
- How to get the client IP address in PHP? 23 answers
I want to get the client IP address who uses my website. I am using the PHP $_SERVER
superglobal:
$_SERVER['REMOTE_ADDR'];
But I see it can not give the correct IP address using this. I get my IP address and see it is different from my IP address and I can also see my IP address in some website like:
http://whatismyipaddress.com/
I paste the IP address which give my PHP function but this website shows no result about this. How does this problem come about and how can I get IP address of the client?
In PHP 5.3 or greater, you can get it like this:
The simplest way to get the visitor’s/client’s IP address is using the
$_SERVER['REMOTE_ADDR']
or$_SERVER['REMOTE_HOST']
variables.However, sometimes this does not return the correct IP address of the visitor, so we can use some other server variables to get the IP address.
The below both functions are equivalent with the difference only in how and from where the values are retrieved.
getenv() is used to get the value of an environment variable in PHP.
$_SERVER is an array that contains server variables created by the web server.
Here is a function to get the IP address using a filter for local and LAN IP addresses:
q
It also works fine for internal IP addresses: